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.
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.
When you open the file using fstream
:
To read, the file is required to exist.
To write you need to specify a write mode using the needed flags:
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);
^^^^^^^^^^^^^^^
Creates the file if it doesn't exist.
Appends to the existing data in the file when you write:
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;
file >> in
will not read anything, 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:
well, you initialized an object, now to create a file use
file.open();