int question_3()
{
fstream hardware("hardware.dat" , ios::binary | ios::in | ios::out);
if (!hardware)
{
cerr << "File could not be opened." << endl;
exit(1);
}
HardwareData myHardwareData;
for (int counter = 1; counter <= 100; counter++)
{
hardware.write(reinterpret_cast< const char * >(&myHardwareData), sizeof(HardwareData));
}
cout << "Successfully create 100 blank objects and write them into the file." << endl;
.
.
.
結果:
爲什麼該文件無法打開?
如果文件「hardware.dat」不存在,程序將創建具有該名稱的文件。爲什麼不?
如果我第一次創建如下文件,程序將繼續。
![在這裏輸入的形象描述] [2]
感謝您的關注。
最終解決方案:
int question_3()
{
cout << "Question 2" << endl;
fstream hardware; <---Changed
hardware.open("hardware.dat" , ios::binary | ios::out); <---Changed
if (!hardware)
{
cerr << "File could not be opened." << endl;
exit(1);
}
HardwareData myHardwareData;
for (int counter = 1; counter <= 100; counter++)
{
hardware.write(reinterpret_cast< const char * >(&myHardwareData), sizeof(HardwareData));
}
cout << "Successfully create 100 blank objects and write them into the file." << endl;
hardware.close(); <---Changed
hardware.open("hardware.dat" , ios::binary | ios::out | ios::in); <---Changed
.
.
.
那麼如何獲得許可?我不確定程序是否應該正常創建文件「hardware.dat」以便繼續。 – Casper