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

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.

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

One comment:

Leave a Reply

Your email address will not be published. Required fields are marked *