【问题标题】:When does program recognize EOF?程序何时识别 EOF?
【发布时间】:2015-03-21 11:50:42
【问题描述】:

我做了一个简单的 C 代码来比较两个文件流。两者都在读取 .txt 文件并将其读取的内容写入新的 .dat 文件(二进制)。问题是结果文件根据光标在 .txt 文件中的位置而有所不同,这意味着文件末尾是否存在'\n'。左大写的最后一句没有'\n',但右大写有。我认为这与“程序何时通知'EOF'?”有关。请帮我。

代码如下。

#include <stdio.h>
#include <string.h>

int main(){
    FILE* src = fopen("/Users/Chois/Desktop/test.txt", "rt");
    FILE* dest = fopen("/Users/Chois/Desktop/dest.dat", "wb");

    char buff[50];
    int countOfWirte = 0;

    if(src!=NULL && dest!=NULL){
        fgets(buff, 50, src);
        while(!feof(src)){
            fwrite(buff, sizeof(char), 50, dest);
            countOfWirte++;
            fgets(buff, 50, src);
         }
    }else{
        printf("fail");
    }

    printf("fwrite work %d times\n", countOfWirte);

    fclose(src);
    fclose(dest);
}

谢谢。

【问题讨论】:

    标签: c file stream


    【解决方案1】:

    将while条件改为

    while (fgets(buff, 50, src) != NULL)
    

    当fgets() 尝试读取EOF 之外的内容时,指示符已设置,因此feof() 将在读取失败后返回true,如果您改为检查fgets() 的返回值,它将返回@987654327 @ 在文件末尾,你会避免这个问题。

    这个问题经常被问到,有一个很好的答案here

    另外,你不应该这样做

    fwrite(buff, sizeof(char), 50, dest);
    

    因为你不知道50chars在哪里读取成功,所以改用fread()like

    size_t readBytes; 
    
    while ((readBytes = fread(buf, 1, sizeof(buf), src)) > 0)
    {
        fwrite(buf, 1, readBytes, dest);
        countOfWrite++;
    }
    

    或者如果您想从文件中读取行,那么fprintf() 将是合适的

    while (fgets(buf, sizeof(buf), src) != NULL)
    {
        fprintf(dest, "%s", buf);
        countOfWrite++;
    }
    

    哦,sizeof(char) 必须是 1。

    【讨论】:

    • 谢谢,真的很有帮助:)
    猜你喜欢
    • 2011-04-27
    • 2011-11-27
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    相关资源
    最近更新 更多