用c++对文件进行后续的读写操作

Subsequent read and write operation on Files with C++

本文关键字:读写 操作 c++ 文件      更新时间:2023-10-16

我有一个二进制文件(test.bin),其中有2个unsigned int值分别为1000和4000。使用下面的代码,我想用第一个write函数将第一个数字更改为5000,然后我想读取第二个数字并将其重写为4000-2000 = 2000。但是,程序将1000更改为5000,但不会将4000更改为2000。即使我使用file.flush()或file.sync(),它也没有任何效果。有趣的是,当我放入file.tellg()或file.tellp()时,它可以按我的要求工作。(我是偶然发现的)这在Linux和Windows上都会发生。在Linux上,我尝试用g++编译它。sizeof(unsigned int)=4,我确信程序可以打开test.bin。

#include <fstream>
#include <iostream>
using namespace std;
int main(){
    fstream file;
    unsigned int data, buffer;
    data=5000;
    file.open("test.bin", ios::binary | ios::in | ios::out);
    file.write((char*)&data,4); // will change first number to 5000
    // file.flush();  // Nothing changes if I delete comment signs.
    // file.tellp();  // Program works correctly if I uncomment this. 
    // file.tellg();  // Program works correctly if I uncomment this.
    file.read((char*)&buffer, 4);  // position pointer should be at the beginning of the 2nd number
    file.seekp(-4, ios::cur); // Since internal pointer is at the end of the file after the read(), I manually put it back to the beginning of the 2nd number.
    buffer-=2000;
    file.write((char*)&buffer,4); // Now, it should rewrite 2nd number with 2000. 
    file.close();
    return 0;
}

答对了!您偶然发现了c++语言的一个非常模糊的、几乎没有写出来的、充其量也就是模棱两可的要求。我试图主张将其从g++中删除,并为此编写了一个补丁,但是在我证明无需大量重新设计即可完成后,维护者对的反应不温不火被接受。

如果内存可用,c++规范提到文件流与C <stdio.h>流具有相同的语义,并且C规范说在读取和写入同一文件之间必须seek

错误如下:http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45708

讨论#1:http://gcc.gnu.org/ml/libstdc++/2010-09/msg00079.html

讨论#2:http://gcc.gnu.org/ml/libstdc++/2010-09/msg00104.html

EDIT:我需要更好的记忆!实际上,是在2010年9月22日提交到GCC 4.6.0中的。其余未提交的编辑与I/o期间更改区域编码方面有关。

跟踪已接受更改的bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45628