在我的项目中,需要读取和写入二进制文件,基本上是在文件中序列化链表,我以二进制格式存储值并记住tellp()/tellg()偏移量,但是,我做不到那。这会将其中的所有内容擦除为零,而不是插入它,而是将当前内容推回。
例如,在下面的程序中,我打开一个文件,写入值 1,120,323。然后关闭它并阅读它,它显示了准确的正确值 1,120,323。但是当我尝试替换 120->220 的值时,1 变为 0,读取为 0 220 220。基本上 220 重写并将 323 推回。
#include <iostream>
#include <fstream>
#include <cstdlib>
int main() {
std::cout<<"File Ofstream Testing "<<std::endl;
const char * file_name = "Test_File.bin";
int ONE = 1;
int ZERO = 0;
int ONE_TWENTY = 120;
int TWO_TWENTY = 220;
int THREE_TWENTY_THREE = 323;
int THREE_FORTY_FIVE = 345;
//---------------------------------------------------------------------------
{
std::ofstream file_write(file_name, std::ios::out|std::ios::binary);
if(!(file_write.is_open())) {
std::cout<<"File cannot be opened "<<std::endl;
exit(0);
}
file_write.seekp(0);
file_write.write((char *)&ONE,sizeof(int));
file_write.write((char *)&ONE_TWENTY,sizeof(int));
file_write.write((char *)&THREE_TWENTY_THREE,sizeof(int));
file_write.close();
}
//---------------------------------------------------------------------------
{
std::ifstream file_read(file_name,std::ios::in|std::ios::binary);
if(!(file_read.is_open())) {
std::cout<<"File cannot be opened "<<std::endl;
exit(0);
}
int temp;
file_read.seekg(0);
file_read.read((char *)&temp,sizeof(int));
std::cout<<"Temp "<<temp<<std::endl;
file_read.read((char *)&temp,sizeof(int));
std::cout<<"Temp "<<temp<<std::endl;
file_read.read((char *)&temp,sizeof(int));
std::cout<<"Temp "<<temp<<std::endl;
file_read.close();
}
//---------------------------------------------------------------------------
{
std::ofstream file_write(file_name, std::ios::out|std::ios::binary);
if(!(file_write.is_open())) {
std::cout<<"File cannot be opened "<<std::endl;
exit(0);
}
file_write.seekp(sizeof(int));
file_write.write((char *)&TWO_TWENTY,sizeof(int));
file_write.seekp(sizeof(int) + sizeof(int));
file_write.write((char *)&THREE_FORTY_FIVE,sizeof(int));
file_write.close();
}
//--------------------------------------------------------------------------
{
std::ifstream file_read(file_name,std::ios::in|std::ios::binary);
if(!(file_read.is_open())) {
std::cout<<"File cannot be opened "<<std::endl;
exit(0);
}
int temp;
file_read.seekg(0);
file_read.read((char *)&temp,sizeof(int));
std::cout<<"Temp "<<temp<<std::endl;
file_read.seekg(sizeof(int));
file_read.read((char *)&temp,sizeof(int));
std::cout<<"Temp "<<temp<<std::endl;
file_read.seekg(sizeof(int) + sizeof(int));
file_read.read((char *)&temp,sizeof(int));
std::cout<<"Temp "<<temp<<std::endl;
file_read.close();
}
//--------------------------------------------------------------------------------
return 0;
}//fn:main