这是我的节目:
#include <iostream>
int main()
{
    // open file1.txt
    FILE* file1;
    fopen_s(&file1, "file1.txt", "wb+");
    // write array of 5 integers to file.txt
    int array1[5] { 1, 2, 3, 4, 5 };
    for (int i = 0; i < 5; i++)
    {
        fwrite(array1, sizeof(array1[0]), 5, file1);
    }
    fseek(file1, 0, SEEK_SET);
    int tempValue;
    fread(&tempValue, sizeof(tempValue), 1, file1);
    // fseek(file1, 0, SEEK_CUR);
    fwrite(&tempValue, sizeof(tempValue), 1, file1);
}在运行时,程序使用信息崩溃:
>     Expression ("Flush between consecutive read and write.",                 
>     !stream.has_any_of(_IOREAD))但是,如果我取消注释fseek(file1, 0, SEEK_CUR);,考虑到文件指针没有被移动,一切都会很好。那这是为什么?我使用2019
为什么这一切都很好?
#include <iostream>
int main()
{
    FILE* file1;
    fopen_s(&file1, "data.txt", "wb+");
    int value = 7;
    fwrite(&value, sizeof(value), 1, file1);
    fwrite(&value, sizeof(value), 1, file1);
    fseek(file1, 0, SEEK_CUR);
    fwrite(&value, sizeof(value), 1, file1);
    fread(&value, sizeof(value), 1, file1);
}发布于 2020-05-10 04:23:50
读写
当指定"r+“、"w+”或"a+“访问类型时,允许读写。(据说该文件是为“更新”打开的。)但是,当您从读到写时,输入操作必须遇到EOF标记。如果没有EOF,则必须使用对文件定位函数的中间调用.文件定位功能有fsetpos、rewind和rewind.从写到读时,必须使用对fflush或文件定位函数的中间调用。
在读/写操作之间进行更改需要一个文件位置函数,在您的代码片段中,您有:
...
fseek(file1, 0, SEEK_SET);
int tempValue;
fread(&tempValue, sizeof(tempValue), 1, file1);
// fseek(file1, 0, SEEK_CUR);
fwrite(&tempValue, sizeof(tempValue), 1, file1);
...由于您正在从读到写,您需要调用一个文件位置函数(fsetpos,寻找或倒带)。
写读
至于写读,您仍然需要调用文件位置函数.然而,要回答第二个代码块为什么工作,我们需要知道fwrite()在成功时做了什么。
根据相同的Microsoft文档的说法
..。fwrite函数写入从缓冲区到输出流的大小为每个项的计数项。与流关联的文件指针(如果有)由实际写入的字节数递增。
考虑您提供的代码:
...
FILE* file1;
fopen_s(&file1, "data.txt", "wb+");
int value = 7;
fwrite(&value, sizeof(value), 1, file1);
fwrite(&value, sizeof(value), 1, file1);
fseek(file1, 0, SEEK_CUR);
fwrite(&value, sizeof(value), 1, file1);
fread(&value, sizeof(value), 1, file1);
...假设所有fwrite()都成功,您的文件指针将位于EOF. 由于输入操作遇到EOF,代码块将执行得很好。
然而,您应该遵循指导方针,调用fsetpos,查找或倒带,如果fwrite失败。
类似的堆栈溢出问题
https://stackoverflow.com/questions/61702763
复制相似问题