求解:怎么用C把文件从后往前读取要求:打印出文件最后一行,然后倒数第二行,第三行,一次类推[解决办法]fseek
求解:怎么用C把文件从后往前读取
要求:
打印出文件最后一行,然后倒数第二行,第三行,一次类推
[解决办法]
fseek到末尾,然后向移动到到上一个结束符,然后去后面字符
[解决办法]
将文件按行读出,存入一个字符指针数组,逆序输出,如果文件大,分块
[解决办法]
[解决办法]
以前寫的,樓主可以完善一下:
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>void tail(int fd, int nline);int main(int argc, char *argv[]){ int line; char *fname; int fd; if (argc != 3) { fprintf(stderr, "Usage: a.out line file\n"); exit(1); } line = atoi(argv[1]); fname = argv[2]; if ((fd = open(fname, O_RDONLY)) == 0) { perror(NULL); exit(1); } tail(fd, line); close(fd); return 0;}void tail(int fd, int nline){ char buf[100] = { 0 }; long n = 0; nline++; while (lseek(fd, n, SEEK_END) && nline) { read(fd, buf, 1); if (!strcmp(buf, "\n")) nline--; n--; } n += 2; /*read postion is before "\n", add 2 to skip to the next line's start */ lseek(fd, n, SEEK_END); while (read(fd, buf, 1)) write(1, buf, 1);} 