代码:
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
.
.
.
为什么要同时使用ios::in
和ios::out
标志打开文件(似乎只在写入该文件)?ios::in
将需要一个现有文件:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream f1("test1.out", ios::binary | ios::in | ios::out);
if(!f1)
{
cout << "test1 failed\n";
}
else
{
cout << "test1 succeded\n";
}
fstream f2("test2.out", ios::binary | ios::out);
if(!f2)
{
cout << "test 2 failed\n";
}
else
{
cout << "test2 succeded\n";
}
}
输出:
burgos@olivia ~/Desktop/test $ ./a.out
test1 failed
test2 succeded
也许您想使用ios::app
?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句