Skip to content

Instantly share code, notes, and snippets.

@LeslieZhu
Last active May 9, 2019 12:49
Show Gist options
  • Save LeslieZhu/8115772 to your computer and use it in GitHub Desktop.
Save LeslieZhu/8115772 to your computer and use it in GitHub Desktop.
C语言实现的程序,读取并打印文件最后N行
#include <stdio.h>
/*
* Author: Leslie Zhu
* Email: [email protected]
*/
/*
* @num : the last num line of file to display
* @files: a file list
* @len : the length of @files list
*
* @return: void
*
*
* sum of the '\n' to get the position of last @num line,
* thus display the last @num line one by one
*/
void tail(int num, char *files[],int len){
FILE *fp;
char buf[1024];
char ch;
int i = 0;
int pos = 0;
int count = 0;
int length = 0;
for (i=0; i < len; i++){
fp = fopen(files[i],"r");
if (NULL == fp){
printf("Can not open file %s\n",files[i]);
}
if(1 < len){
printf("==> %s <==\n",files[i]);
}
pos = -1;
count = 0;
length = 0;
while(count <= num){
if(ftell(fp) == (SEEK_SET+1)){
fseek(fp,0,SEEK_SET);
break;
}
fseek(fp,pos,SEEK_END);
pos -= 1;
ch = fgetc(fp);
if(ch == '\n'){
count += 1;
}
if(length == 0){
length = ftell(fp);
}
}
while(feof(fp) != 1){
if (ftell(fp) == length){
break;
}
fgets(buf,1024,fp);
printf("%s",buf);
fflush(fp);
}
fclose(fp);
}
}
int main(int argc, char **argv){
char *files[argc];
int i = 1;
if (3 > argc){
printf("Usage: %s num FILE1 [FILE2..]\n", argv[0]);
return -1;
}
for (i = 2; i < argc; i++){
files[i-2] = argv[i];
}
tail(atoi(argv[1]),files,argc-2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment