4

I want to create an empty file in ubuntu with c++ and i tried many ways and it keeps failing and show this error

error: no matching function to 'std::basic_ofstream::open(std::cxxll::...

my code:

ifstream f(saltFile.c_str());

if (f.good())
{
     cout << saltFile + " file already existed" << endl;
}
else
{
    ofstream file;
    file.open (saltFile, ios::out);
    cout << saltFile << " created!" << endl;
}
user0042
  • 7,917
  • 3
  • 24
  • 39
kerrysugu
  • 123
  • 1
  • 1
  • 9
  • 3
    Possible duplicate of [Creating files in C++](https://stackoverflow.com/questions/478075/creating-files-in-c) – Mureinik Aug 28 '17 at 15:53
  • `file.open (saltFile.c_str(), ...`. The C++98 version has only a prototype with `const char *`: http://www.cplusplus.com/reference/fstream/ofstream/open/ – mch Aug 28 '17 at 15:54
  • 1
    What compiler are you using? Did you enable C++11 or higher? – NathanOliver Aug 28 '17 at 15:55
  • Creating an empty file is not 1:1 with creating files in general, so I agree that this is not a duplicate question. There are challenges to account for with empty file creation such as avoiding accidental encoding, empty lines, etc. – kayleeFrye_onDeck Jan 31 '19 at 00:18

3 Answers3

14

If you want a completely empty file, you can use <fstream>'s std::ofstream, and not even call the object.

Note: this assumes that the file does not already exist. If it does then you should remove it first if you want it replaced with a blank file.

Empty file creation

std::ofstream output(file_path);

Creating a file with content

std::ofstream output(file_path);
output << L"Hello, world!";

Funny side-note:

Before trying out just using ofstream's constructor I tried output << nullptr; to see what would happen...

enter image description here

Precious

kayleeFrye_onDeck
  • 6,648
  • 5
  • 69
  • 80
  • 2
    Note from noob to self: calling `std::ofstream(file_path);` works too if you don't need to keep a handle pointing to the opened file and just want to "touch" the file. – Jasha Apr 23 '21 at 00:13
  • If you just open file such way ```std::ofstream output(file_path)```, it would not be created! you need to make ```output.flush()``` somewhere or just make ```std::ofstream(file_path).flush();```. – RUSLoker Jun 10 '22 at 13:10
  • Maybe it's specific to your flavor of C++? What are you using? – kayleeFrye_onDeck Jun 29 '22 at 10:54
3

If you have a C++11 or later compiler, you can certainly use:

else
{
    ofstream file;
    file.open (saltFile, ios::out);
    cout << saltFile << " created!" << endl;
}

If you have a pre-C++11 compiler, the call to open() needs to be tweaked a little bit.

file.open (saltFile.c_str(), ios::out);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

to create a file you can use ofstream

#include <fstream>

int main() {  
std::ofstream outfile;

outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
 outfile << "Data"; 
return 0;
}