c - fwrite() 之后的 fread() 获取 0 个字节

标签 c linux file fedora

我为 FILE* 对象设置了一个大缓冲区(大小为 8 * 1024),我正在向其中写入 4 个字节,然后我读取4,但读取失败。 如果我刷新 FILE* 读取就会成功。

typedef struct _MyFile {                 /* file descriptor */
    unsigned char fileBuf[8*1024];
    FILE *file;
} MyFile;

int main() {
    MyFile myFile;
    int res;
    char bufWrite[4] = { 1, 2, 3, 4 };
    char bufRead[4];

    /* Open file for both reading and writing */
    myFile.file = fopen("myfile.txt", "w");

    /* Change the file internal buffer size */
    setvbuf(myFile.file, myFile.fileBuf, _IOFBF, sizeof(myFile.fileBuf));

    /* Write data to the file */
    res = (int)fwrite(buf, 1, 4, myFile.file);
    printf("write: res = %d\n", res);

    /* Seek to the beginning of the file */
    fseek(fp, SEEK_SET, 0);

    /* Read and display data */
    res = (int)fread(buf, 1, 4, myFile.file);
    printf("read: res = %d\n", res);
    fclose(myFile.file);

    return 0;        
}

输出为:

write: res = 4
read: res = 0

如果我写入超过 8K 或使用 write() 而不是 fwrite()fread() 效果很好。

问题是我不能使用fflush()!!!

有什么办法可以解决吗?

最佳答案

您已以只写模式打开文件。该句柄不知道您要读取它。

只需以读写模式打开文件即可:

myFile.file = fopen("myfile.txt" , "w+");

我已经测试过了,它成功读回了读缓冲区中的数据。

仅写入模式:

write : res = 4
read: res = 0
bufRead: -83 20 82 117

读/写模式:

write : res = 4
read: res = 4
bufRead: 1 2 3 4

编辑:我第一次尝试使用“rw”模式,该模式有效,但给出了奇怪的写入返回值结果:

write : res = 0
read: res = 4
bufRead: 1 2 3 4

关于c - fwrite() 之后的 fread() 获取 0 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40846081/

相关文章:

c - 使用枚举作为参数的奇怪编译行为

linux - 使用 mlockall 使 JVM/Solr 不交换

c - "\__signed" "\__signed__"和 "signed"有什么区别?

linux - 如何通过为每个 Linux 内核启动一个任务来(简单地)与 Linux shell 并行化?

python - 为什么在 Python 中从多个进程写入文件时我的文件没有损坏?

c - Julia:Ptr{Void} 终结器错误

c - C 结构中的箭头与点?

c - 这段代码是什么意思? void (*signal(int sig, void (*func)(int)))(int);

C++ 将 CSV 文件解析为 vector vector : Loosing string 1st character

java - 文件保存 500 个从 0 到 1000 的随机数。将这些数字写入文件,然后打开文件并一一读取数字