[c++] fstream won't create a file

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 question is related to c++ file-io fstream

The answer is


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

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to fstream

clear data inside text file in c++ fstream won't create a file C++: variable 'std::ifstream ifs' has initializer but incomplete type How to read line by line or a whole text file at once? Using C++ filestreams (fstream), how can you determine the size of a file? Reading from text file until EOF repeats last line