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