Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fstream won't create a file [duplicate]

Tags:

I'm simply trying to create a text file if it does not exist and I can't seem to get fstream to do this.

#include <fstream> using std::fstream;  int main(int argc, char *argv[]) {     fstream file;     file.open("test.txt");     file << "test";     file.close(); } 

Do I need to specify anything in the open() function in order to get it to create the file? I've read that you can't specify ios::in as that will expect an already existing file to be there, but I'm unsure if other parameters need to be specified for a file that does not already exist.

like image 431
raphnguyen Avatar asked Mar 27 '13 19:03

raphnguyen


People also ask

How to use fstream in C++ with example?

Below is a simple syntax for the fstream in the c++. In the below example first we are getting or creating a file, we can give any name to file which we are creating here. Second we are writing some contents to the file. In the same way we can read the file content with help of the getline function in while loop. How fstream work in C++?

Why does ofstream only create a file?

For your first question, ofstream only creates a file because it does not depend on any information contained inside the file. All ofstream does is write to files, so if it creates a new, blank file, this doesn't interfere with writing information to it. An ifstream cannot create files, because an ifstream is supposed to be reading data.

How to create a file if file does not exist in C++?

So for that case we have fstream c++ package. We can create a file if file does not exists like. Here first we can create a file instance with code like “ofstream of”, here of will be used as the instance. Next we can pass any name of file which we want to create like “open (any filename);”.


1 Answers

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out); 

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/

like image 182
haitaka Avatar answered Sep 28 '22 03:09

haitaka