如何实现tail -n linux命令 [英] How to implement tail -n linux command
本文介绍了如何实现tail -n linux命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试实现tail -n函数,但效率不高,你能帮助我以另一种方式实现吗?这是我的代码
函数必须显示文件的最后n行
谢谢!
我尝试过:
I try to implement tail -n function, but it is not efficiently, can you help me to implement in another way ? This is my code
function must display the last n lines of the file
Thanks!
What I have tried:
void tail_n(){
m=atoi(params[2]);
file_name1=fopen(params[3],"r");
if ( file_name1 != NULL )
{
while (fgets(line, 199, file_name1) != NULL)
{
count++;// numarul de linii din fisier
}
count1=count-m;// nr de linii de unde incep afisarea
file_name1=fopen(params[3],"r");
if(file_name1 !=NULL)
{
while (fgets(line,199,file_name1)!=NULL)
{
if(afisare>=count1)
printf("%s",line);
afisare++;
}
count=0; count1=0;
}
else perror("Eroare");
}
else perror("Eroare");
fclose ( file_name1 );;
推荐答案
为什么要打开文件两次(即使打开文件也只关闭一次)失败了)?
你应该看一下倒带 - C ++参考a> [ ^ ]功能。
为了加快执行速度,您还可以使用m
项目分配一个环形缓冲区来存储行位置。然后你可以使用 fseek - C ++ Reference [ ^ ]最低位置跳转到要打印的第一行。
未经测试的片段:
Why do you open the file twice (and close it only once even when opening fails)?
You should have a look at the rewind - C++ Reference[^] function.
To speed up execution you can also allocate a ring buffer withm
items to store the line positions. Then you can use fseek - C++ Reference[^] with the lowest position to jump to the first line to be printed out.
Untested snippet:
long int *positions = (long int *)malloc(m * sizeof(long int));
int pos = 0;
int last_pos = 0;
positions[0] = 0;
while (fgets(line, 199, file_name1) != NULL)
{
if (++pos >= m)
pos = 0;
positions[pos] = ftell(file_name1);
last_pos = pos;
count++;
}
if (count < m || ++last_pos >= m)
last_pos = 0;
fseek(file_name1, positions[last_pos], SEEK_SET);
while (fgets(line, 199, file_name1) != NULL)
{
printf("%s",line);
}
free(positions);
您已在 tail -c命令linux,用c实现 [ ^ ]。请不要重新发布。
You already posted this question at tail -c command linux, implement with c[^]. Please do not repost.
这篇关于如何实现tail -n linux命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文