简体   繁体   English

fseek和feof的用法

[英]Usage of fseek and feof

I this code is used for reading the text file in reverse order. 我此代码用于按相反顺序读取文本文件。 And it successful does, displaying the original content of file and the reversed content of file. 它成功了,显示了文件的原始内容和文件的反向内容。

#include <stdio.h>
#include <stdlib.h>
int main()  {

    int count = 0, ch = 0;
    FILE *fp;
    if( (fp = fopen("file.txt", "r")) == NULL )    {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    printf("\tINPUT FILE\n");
    printf("\n");
    while(!feof(fp))    {
        if((ch = getc(fp)) != EOF)  {
            printf("%c", ch);
            count ++;
        }
    }
    feof(fp);
    printf("\n");
    printf("\tREVERSED INPUT FILE\n");
    printf("\n");
    while(count)    {
        fseek(fp, -2, SEEK_CUR);
        printf("%c", getc(fp));
        count--;
    }
    printf("\n");
    fclose(fp);
}

But when i replaced, this piece of code 但是当我替换时,这段代码

while(!feof(fp))    {
   if((ch = getc(fp)) != EOF)  {
       printf("%c", ch);
       count ++;
   }
}

by 通过

fseek (fp, 0, SEEK_END); or  feof(fp);

Basically i just went till end of file and directly without printing the original contents of file and tried printing the reversed content of file. 基本上我只是一直走到文件末尾,而没有直接打印文件的原始内容,而是尝试打印文件的反向内容。 But for it does not print the reversed content filed either !!! 但是因为它不打印提交的反向内容! it just display blank. 它只是显示空白。 Why is this happening ?? 为什么会这样?

NOTE: fseek(fp, -2, SEEK_CUR); 注意: fseek(fp, -2, SEEK_CUR); Have done this (in another while loop) as getc(fp) moves fp forward by one so need to rewind it back by two, also initially it will be pointing to EOF 完成此操作(在另一个while循环中),因为getc(fp)将fp向前移动一个,因此需要将其后退两个,而最初它也将指向EOF

What is happening here? 这是怎么回事 Can any one please explain? 有人可以解释一下吗?

It breaks because the second loop is while (count) , and count is zero if you haven't read through the file first while incrementing it. 它之所以中断,是因为第二个循环是while (count) ,如果您在递增文件时没有先读完文件, count就是零。 You can use ftell to obtain the equivalent of count in this case. 在这种情况下,您可以使用ftell获得等效count

PS feof(fp) only tests whether fp is at end-of-file, it does not make it seek to EOF, so the line feof(fp) basically does nothing since you aren't using the return value. PS feof(fp)仅测试fp是否在文件末尾,它不会使其寻求EOF,因此feof(fp)基本上不执行任何操作,因为您没有使用返回值。

As @Arkku already showed, when you replace the while loop with fseek(SEEK_END) , count will not be incremented. 正如@Arkku已经显示的那样,当您用fseek(SEEK_END)替换while循环时, count不会增加。

To fix this, you can use ftell after fseek , which returns the file length 要解决此问题,可以在fseek之后使用ftell ,它返回文件长度

fseek(fp, 0, SEEK_END);
count = ftell(fp);

Now the file will be printed backwards. 现在,文件将向后打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM