gpt4 book ai didi

c++ - "File could not be opened."C++ fstream

转载 作者:行者123 更新时间:2023-11-30 01:19:02 25 4
gpt4 key购买 nike

代码:

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;
.
.
.

结果:

enter image description here

为什么文件打不开?

如果文件“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
.
.
.

enter image description here

最佳答案

你为什么要用 ios::inios::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

关于c++ - "File could not be opened."C++ fstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21602623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com