fwrite() 后的 fread() 获得 0 个字节

fread() after fwrite() gets 0 bytes

我为 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

read/write模式:

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

编辑:我第一次尝试使用 "rw" 模式,虽然有效但给出了奇怪的写入 return 值结果:

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