如何正確地將數據從二進制文件寫入新的字符數組。 我知道這個問題在這裏被問了幾次,但我仍然無法弄清楚如何正確地做到這一點。如何正確地從二進制文件讀取數據到字符數組
這是我迄今..
struct Computer_Details {
char computer_type[99];
int release_year;
float price;
};
Computer_Details pc_details;
cout << "Enter Computer Type: ";
cin.getline(pc_details.computer_type, 255);
cout << "Enter Computer Release Date: ";
cin >> pc_details.release_year;
cout << "Enter Computer Price: ";
cin >> pc_details.price;
cout << "\n\n";
//Create File
ofstream file;
file.open("PC_Database.data", ios::binary | ios::app);
if (!file) cout << "Couldn't open file\n";
else {
file.write((char*)&pc_details, sizeof(Computer_Details));
file.close();
}
ifstream readFile;
readFile.open("PC_Database.data", ios::binary);
if (!readFile) cout << "Couldn't Open File\n";
else {
readFile.seekg(0, ios::end);
int fileSize = readFile.tellg();
int pcCount = fileSize/sizeof(Computer_Details);
readFile.seekg(0, ios::beg);
Computer_Details *pc_details = new Computer_Details[pcCount];
readFile.read((char*)pc_details, pcCount * sizeof(Computer_Details));
char *buff = new char[299];
for (int i = 0; i < pcCount; i++)
{
//write to buff char
}
readFile.close();
}
你可以使用['strcpy'](http://en.cppreference.com/w/cpp/string/byte/strcpy)。 –
可能重複[讀取二進制文件到char數組在c + +](http://stackoverflow.com/questions/33935567/reading-binary-file-into-char-array-in-c) – didiz
這個答案沒有幫助 – Andrew