在fwrite()得到0字节之后,fread()。

时间:2021-12-29 20:21:05

I am set a big buffer for the FILE* object(size of 8 * 1024) and I'm making a write of 4 bytes to it and then I read of the 4, but the read fail. If I flush the FILE* the read succeeds.

我为FILE* object设置了一个大的缓冲区(大小为8 * 1024),我对它写了4个字节,然后读取了4个字节,但是读取失败了。如果我刷新文件*读取成功。

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;        
}

The output is:

的输出是:

write: res = 4
read: res = 0

If I write more than 8K or use write() instead of fwrite() the fread() works well.

如果我写了超过8K或使用write()而不是fwrite(),那么fread()就可以很好地工作。

The thing is I can't use fflush()!!!

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

Is there any way to fix it?

有什么办法解决它吗?

1 个解决方案

#1


2  

You have opened your file in write-only mode. The handle isn't aware that you want to read on it.

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

Just open your file in read-write mode:

以读写模式打开文件:

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

I have tested it and it successfully reads back the data in the read buffer.

我已经对它进行了测试,它成功地读取了读取缓冲区中的数据。

write mode only:

只写模式:

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

read/write mode:

读/写模式:

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

Edit: my first attempt use "rw" mode which worked but gave strange write return value result:

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

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

#1


2  

You have opened your file in write-only mode. The handle isn't aware that you want to read on it.

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

Just open your file in read-write mode:

以读写模式打开文件:

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

I have tested it and it successfully reads back the data in the read buffer.

我已经对它进行了测试,它成功地读取了读取缓冲区中的数据。

write mode only:

只写模式:

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

read/write mode:

读/写模式:

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

Edit: my first attempt use "rw" mode which worked but gave strange write return value result:

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

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