点击(此处)折叠或打开
- #include<stdio.h>
- #include<strings.h>
- #define MAX_SIZE 1024
- /* 将一个文件的最后一行作为第一行输出,依次输出逆序的文件*/
- static int
- ReverseFile(const FILE *in){
- FILE *fp = in;
- long cur,start;
- char buf[MAX_SIZE] = { 0 }; // 作为读取文件的缓冲
- char c;
- long i = -2;
- start = ftell (fp);
- fseek (fp,-2l,SEEK_END); // 将文件指针指向最后一个字符,并不是 eof ,并不会改变fp的值
- cur = ftell (fp);
- while (cur >= start){
- c = fgetc (fp);
- if (cur == 0 || c == '\n'){
- fgets (buf,MAX_SIZE,fp);
- }
- if (cur == 0){ // 为了解决第一行为换行的情况
- fseek (fp,0l,SEEK_SET);// fgetc 读取的字符为当前cur后一个字符,所以将读取位置置为开始
- c = fgetc (fp); // 读取第一个字符
- if (c != '\n') // 判断第一个字符是什么字符,根据是否为换行符做出相应的决策
- {
- fprintf (stdout,"%c",c);
- fprintf (stdout,"%s",buf);
- }
- else{
- fprintf (stdout,"%s",buf);
- fprintf (stdout,"%c",c);
- }
- break;
- }
- fprintf (stdout,"%s",buf);
- bzero (buf,MAX_SIZE);
- fseek (fp,--i,SEEK_END);
- cur = ftell (fp);
- }
- return 0;
- }
- int
- main(int argc,char* argv[])
- {
- FILE *file;
- if (argc != 2)
- return -1;
- file = fopen (argv[1],"r");
- if (file == NULL)
- {
- perror ("Error");
- return -1;
- }
- ReverseFile (file);
- fclose (file);
- return 0;
- }