“文件无法打开。” C ++ fstream

时间:2014-02-06 12:11:27

标签: c++ file file-io fstream ifstream

代码:

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

3 个答案:

答案 0 :(得分:3)

为什么要用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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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