【问题标题】:"File could not be opened." C++ fstream“文件无法打开。” C++ 流
【发布时间】: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


【解决方案1】:

您为什么要同时使用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

【讨论】:

  • OIC...由于接下来要阅读,所以我写了 ios::in 和 ios::out。你的意思是我必须在下面的行中输入 fstream hardware("hardware.dat", ios::in | ios::binary) 。是不是更合适??谢谢
  • 如果我输入 "fstream hardware("hardware.dat" , ios::binary | ios::out | ios::in);"在以下行中,它导致构建失败。然后我尝试通过在上一行中添加“删除硬件”来解决这个问题,但它不起作用。我能做些什么?谢谢
  • @CasperLi 关闭文件然后再次打开。
【解决方案2】:

当您同时指定ios::inios::out 时,该文件必须存在 - 它不会被创建。

如果您只是在写作,请仅使用ios::out

【讨论】:

    【解决方案3】:

    ios::in 指定您要打开现有文件进行读取。既然你不想读任何东西,你应该坚持ios::out,如果文件不存在,它将创建文件并打开它进行写入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 2019-02-10
      • 1970-01-01
      • 2014-10-21
      • 2015-12-17
      相关资源
      最近更新 更多