用c++对文件进行后续的读写操作
Subsequent read and write operation on Files with C++
我有一个二进制文件(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
- 用C++快速读写文件
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 在一个读写器队列中,我可以用volatile替换原子吗
- C++套接字对不读/写父/子
- 如何调试读写器锁的死锁?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- Linux 挂载使用重新挂载以允许读写
- C++中读/写二进制文件
- 如何读/写或遍历 std::array 中的特定元素范围?
- 内存排序或读取-修改-写入操作,仅(读/写)内存顺序
- USB-HID 读/写(重叠)等待单个对象不返回C++
- 在 c++ 中使用 std::atomic 的比较和读/写操作<bool>?
- C++队列中读/写操作的顺序
- 读/写操作既不好也不坏
- 使用运算符[]时如何区分读/写操作
- 为特定的读写操作重载下标运算符
- 用c++对文件进行后续的读写操作
- 在读/写操作中使用c++ 11 unordered_map的最有效方法
- 如何在Visual Studio中打开fstream进行读写操作