Search code examples
c++filefile-iofstreamifstream

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


Code :

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

Result :

enter image description here

Why the file could not be opened?

If the file "hardware.dat" do not exist, the program will create the file with that name. Why not?

If I first create the file like the following, the program will continue.

![enter image description here][2]


Thank you for your attention.


Final Solution :

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


Solution

  • Why are you opening your file with both ios::in and ios::out flags (it seems that you're only writing to this file)? ios::in will require an existing file:

    #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";
        }
    }
    

    output:

    burgos@olivia ~/Desktop/test $ ./a.out 
    test1 failed
    test2 succeded
    

    Maybe you want to use ios::app?