fwrite()得到0字节后的fread()

时间:2016-11-28 13:57:53

标签: 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() !!!

有没有办法解决它?

1 个答案:

答案 0 :(得分:2)

您已在只写模式下打开文件。句柄不知道您想要阅读它。

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

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