我想用单个文件流读写一个二进制文件。下面的代码尝试读取文件的第一部分,并用它来覆盖文件的第二部分。但我发现我必须使用“seekp(pos [,ios_base::begin]);”在写作之前。此外,“seekp”实际上并没有改变我代码中的位置,但这是必要的!任何人都可以解释一下吗?最好是按照c++标准。非常感谢!
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream flib ("tmp.txt", ios::in | ios::out |ios::binary | ios::trunc);
if(!flib){
cerr << "file open failed!" << endl;
return 1;
}
int tmp;
for(int i = 0; i<2 ; i++){//write 2 numbers
flib.write((char*)&i, sizeof(tmp));
}
flib.seekg(0);
while(flib.read((char*)&tmp, sizeof(tmp))){//read file contents
cout <<tmp<<endl;
}
flib.clear();
flib.seekg(0);
flib.read((char*)&tmp, sizeof(tmp));
flib.seekp(sizeof(tmp)); //work
//flib.seekp(sizeof(tmp), ios_base::beg); //work
//flib.seekp(0, ios_base::cur); //not work
//flib.seekp(sizeof(tmp), ios_base::end); //not work
//flib.seekp(-sizeof(tmp), ios_base::end); //not work
flib.write((char*)&tmp, sizeof(tmp));
flib.clear();
flib.seekg(0);
while(flib.read((char*)&tmp, sizeof(tmp))){//read file contents
cout <<tmp<<endl;
}
return 0;
}
评论:我发现如果我使用 flib.seekp(some_number, ios_base::cur);使用非零 some_number,它可以工作。而且我用的是vs2012 express编译器,是bug吗?
最佳答案
文件流使用 basic_filebuf<>
用于流缓冲区。 C++03 标准对 class basic_filebuf<charT,traits>
有这样的说法:
27.8.1.1 Class tempate basic_filebuf
The class basic_filebuf associates both the input sequence and the output sequence with a file.
The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library
FILE
s.In particular: - If the file is not open for reading the input sequence cannot be read. - If the file is not open for writing the output sequence cannot be written. - A joint file position is maintained for both the input sequence and the output sequence.
不幸的是,在对 FILE
进行读写转换时,它并没有指出这一点。使用标准 C 库的对象,您必须执行文件定位调用(或从写操作转换为读操作时的 fflush()
)。参见 https://stackoverflow.com/a/14879076/12711 .
关于c++ - 在写作之前搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240410/