各位帮忙改一下,打印文本文件的最后n行。
打印文本文件的最后n行
unix中的一条命令:tail -n filename
-n 表示要打印的函数,默认的行数是10
用循环链表来实现这个功能。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define DEFLINES 10
#define MAXSIZE 100
char buf[MAXSIZE];
struct tail{
char *data;
struct tail *link;
};
void main(int argc,char* argv[])
{
FILE *file_handle;
int i,n = DEFLINES;
char *filename;
tail *current,*p,*list = NULL;
scanf("%s",buf);
if(argc == 3&&argv[1][0] == '-')
{
n = atoi(argv[1]);
filename = argv[2];
}
else if(argc == 2)
filename = argv[1];
else
{
printf("Error.Usage:tail -n filename.\n");
exit(1);
}
file_handle = fopen(filename,"r");
if(file_handle == NULL)
printf("Cannot open the file %s\n",filename);
exit(1);
/*Creat the CLinkList*/
for(i = 1;i <= n;i++)
{
current = (tail*)malloc(sizeof(struct tail));
current->data = '\0';
if(list == NULL)
list = current;
else
p->link = current;
p = current;
}
p->link = list;
current = list;
while(fgets(buf,80,file_handle) != NULL)
{
strcpy(current->data,buf);
current = current->link;
}
for(i = 1;i <= n; i++)
{
printf("%s\n",current->data);
current =current->link;
}
fclose(file_handle);
}