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.
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++?
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.
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);”.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With