[英]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.