C语言关于fread()多读取一行的问题

2025-06-22 01:25:51
推荐回答(4个)
回答1:

这个是feof造成的,给你写了个示例,你看一下

#include 
int main()
{
    FILE *fp;
    fp = fopen("input.txt", "r");
    fseek(fp, 0, SEEK_END);
    char b[10] = {0};
    int count_file_b = ftell(fp);
    int result;
    fseek(fp, 0, SEEK_SET);
    //count_file_b -= 1;
    printf ("count_file_b=%d\n", count_file_b);
    result = fread(b, count_file_b, 1, fp);
    for (int i = 0; i < 10; ++i){
        printf ("%d ", b[i]);
    }
    printf ("\n");
    printf ("result=%d\n", result);
    while (!feof(fp)){
        printf ("%s\n", b);
        result = fread(b, count_file_b, 1, fp);
        printf ("result=%d\n", result);
    }
    return 0;
}

其中input.txt中保存的是this

输出结果如下:

回答2:

我调试了一下,并没有多取一行。
原因:fwrite(ch,sizeof(ch),1,pf2);}这一步sizeof(ch)是10个字节,所以会写入10个字符,即后面的00写入了2.txt中。
正确写法:fwrite(ch,strlen(ch),1,pf2);}

回答3:

char ch[10] ] {'0'}这里初始化的时候应该给0 不是'0'.

回答4:

请详细解释,谢谢