【发布时间】:2014-02-06 12:11:27
【问题描述】:
代码:
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”以供继续使用。
标签: c++ file file-io fstream ifstream