[英]C++ Binary Read Write Files
好的,所以我在大学第二学期的即时通讯已经完成了c并现在在DevC中完成了c ++的工作。
目前,我正在制作一个程序,将在拥有和编辑数据库的同时执行商店的收费过程。
尝试编写和读取完整的结构但有一定的工作量,因此我放弃编写2个int数并读取它们,但是即使我写txt时数字似乎还可以,但在读取时获得随机数的同时也有一定的工作量。
//write and read are different fucntion only 1 is called .
//file creation code
int AccountNumber=0;
ofstream FileCreator("Database.dat",ios::binary);
FileCreator<<AccountNumber;
AccountNumber=1;
FileCreator<<AccountNumber;
和
//reading code
int AccountNumber=0;
ifstream FileCreator("Database.dat",ios::binary);
FileCreator.seekg(0,ios::beg);
FileCreator.read(reinterpret_cast<char*>(&AccountNumber), sizeof(AccountNumber));
cout<<AccountNumber<<endl;
FileCreator.read(reinterpret_cast<char*>(&AccountNumber), sizeof(AccountNumber));
cout<<AccountNumber<<endl;
我期望输出为0和1,但得到12592和12592。
完成@Thomas Matthews的回答
但是为什么重要呢? <<在二进制文件中写的方式与.write不同吗?
在Windows之外您不会看到任何区别,如果在二进制模式下打开文件,则在Windows下\\ n会保存/读取不变,否则写入\\n
会生成\\r\\n
而读取\\c\\n
则会返回\\n
。 就像fopen的 “ r” /“ rb”和“ w” /“ wb”之间的区别一样。
您可以混合使用运算符<</>>
和在二进制模式下进行读/写操作,但必须注意分隔符,例如:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int AccountNumber = 123;
{
ofstream bin("bin",ios::binary);
bin << AccountNumber << '\n'; // a \n to finish the number allowing to read it later
bin.write((char *) &AccountNumber, sizeof(AccountNumber));
}
{
ofstream txt("txt");
txt << AccountNumber << '\n';
txt.write((char *) &AccountNumber, sizeof(AccountNumber));
}
{
ifstream bin("bin",ios::binary);
AccountNumber = 0;
bin >> AccountNumber;
cout << AccountNumber << endl;
// I have to read the \n with read() because >> bypass it.
// Supposing I written '@' rather than '\n' `bin >> c;` can be used
char c;
bin.read(&c, 1);
cout << (int) c << endl;
AccountNumber = 0;
bin.read((char *) &AccountNumber, sizeof(AccountNumber));
cout << AccountNumber << endl;
}
return 0;
}
编译和执行(Windows以外):
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall f.cc
pi@raspberrypi:/tmp $ ./a.out
123
10
123
pi@raspberrypi:/tmp $ cmp txt bin
pi@raspberrypi:/tmp $
我不在Windows下,所以要使用二进制模式或什么都不更改,这两个文件是相同的
要写入二进制文件,请使用std::ostream::write()
方法,而不要使用operator<<
:
FileCreator.write((char *) &AccountNumber, sizeof(AccountNumber));
强制转换是必需的,因为没有将整数写入流的重载。
请记住, read
和write
是成对的二进制I / O。
编辑1:固定长度和可变长度记录
请注意,在读写时需要物品的大小 。 这将适用于固定大小/长度的数据项和结构。 但是,它不适用于可变长度的数据(例如文本)。
对于可变长度记录,您可能要先写长度,然后写数据:
static const char hello[] = "Hello";
static const unsigned int data_size(sizeof(hello) - 1);
FileCreator.write((char *) &data_size, sizeof(data_size));
FileCreator.write(&hello[0], data_size);
在上面的示例中,“-1”在那里,因此未将终止NUL字符写入文件。 对于二进制文件,您不需要它,但是对于YMMV(在编写控制台和其他人类可读流时使用的是惯用语)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.