1

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.

anastaciu
  • 22,293
  • 7
  • 26
  • 44
  • 1
    Does this answer your question? [std::fstream doesn't create file](https://stackoverflow.com/questions/8835888/stdfstream-doesnt-create-file) – ChrisMM Apr 15 '21 at 08:48
  • That way it doesn't even create anything. `fstream file;` `file.open("test.txt",ios::out | ios::in)` –  Apr 15 '21 at 08:54

2 Answers2

1

When you open the file using fstream:

  • To read, the file is required to exist;

  • To write you need to specify a write mode, ofstream would do that for you, but with fstream you need to do it yourself:


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);
                                                                   ^^^^^^^^^^^^^^^

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);
                                                                   ^^^^^^^^^^^^^

Note that after reading or writing you'll need to set the offset position in the file, for instance:

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:

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

This resets the read position indicator to the beggining of the file, before the file is read from, more about it here:

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

anastaciu
  • 22,293
  • 7
  • 26
  • 44
0

well, you initialized an object, now to create a file use

file.open();

see fstream won't create a file

  • 2
    The constructor should create the file. No need to `open` – bolov Apr 15 '21 at 08:49
  • That way it doesn't even create anything. `fstream file;` `file.open("test.txt",ios::out | ios::in)` –  Apr 15 '21 at 08:55