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.
This will do:
#include <fstream>
#include <iostream>
using std::fstream;
int main(int argc, char *argv[]) {
fstream file;
file.open("test.txt",std::ios::out);
file << fflush;
file.close();
}
You need to add some arguments. Also, instancing and opening can be put in one line:
fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
Source: Stackoverflow.com