在我的项目,有需要读取和写入二进制文件,基本序列化链表在文件中,在这里我以二进制格式存储的值,并记住tellp()/所以tellg()偏移,怎么过,我不能做那。 这将删除所有内容,它为零,而不是插入它使当前的内容了。
例如,在下面的节目,我打开一个文件,写值说1120323。 然后关闭它,阅读它,它显示确切的正确值1120323。 但是当试图替换的120-> 220的值,1变为零,并且值读出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