c++file

Opening a file to read and write, create it if it doesn't exist


I was trying to create a file in both read and write modes, but it doesn't create the file, what can be the problem?

This is code:

fstream file("NameFile.txt", ios::out| ios::in);

The program will start, but it will not create any files.


Solution

  • When you open the file using fstream:


    The bellow code replaces the contents of the file when you write (ofstream default mode):

    std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::trunc);
                                                                     ^^^^^^^^^^^^^^^
    

    It will create the file if it doesn't exist.


    The bellow code appends to the existing data in the file when you write in:

    std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::app);
                                                                     ^^^^^^^^^^^^^
    

    Also creates the file if it doesn't yet exist.


    Having a file opened both to write and read needs some extra attention. For example, say you want to read what you previously wrote, you'll need to set the offset position in the file. Here's some code to illustrate this:

    std::string s = "my string";
    std::string in;
    
    file << s; 
    file >> in;
    

    In the above code file >> in will not read the written data, the position indicator is at the end of the file after file << s, you'll need to reset it if you want to read previously written data, for example using seekg:

    file << s; 
    file.seekg(0);
    file >> in;
    

    This resets the read position indicator to the beginning of the file, before the file is read from.

    Basically you need take care of the indicator's position both to not read from and to not write in the wrong places.


    References:

    https://en.cppreference.com/w/cpp/io/basic_fstream