SysTutorials Forums QA How to create a file if not exist and open it in read and write modes in C++?

Tagged: , ,

How to create a file if not exist and open it in read and write modes in C++? For example, I would like open a fstream on /tmp/cache to be able to read it and append to it. If the file does not exist yet, create one.

A simple code like

std::fstream fs("/tmp/cache", std::ios::in | std::ios::out | std::ios::app);

will not create the file if it does not exist.

use this:
fstream file("myFile.txt", ios::in | ios::app | ios::out);

When fstream is constructed with std::ios::in included, if the file does not exist, the std::ios::in portion fails because the file does not exist. In more details: after calling open() to open the file because std::ios::in is in the mode, fail() will evaluate to true.

Hence, to use a file stream in read/write mode, ensure the file exists first. The following piece of code implements such.

  std::fstream fs;
  fs.open("/tmp/cache", std::ios::out | std::ios::app);
  fs.close();
  fs.open("/tmp/cache", std::ios::in | std::ios::out | std::ios::app);
Reply To: How to create a file if not exist and open it in read and write modes in C++?
Your information:





<a href="" title="" rel="" target=""> <blockquote cite=""> <code> <pre> <em> <strong> <del datetime=""> <ul> <ol start=""> <li> <img src="" border="" alt="" height="" width="">

Please share if you like this post: