Fstream input and output from a nonexistent file

Is it possible to open the fstream file for a file that does not exist with ios :: in and ios :: out without receiving an error?

+7
c ++ fstream
source share
4 answers

Update : To open fstream in a file that does not exist for input and output (random access) without receiving an error, you must provide fstream::in | fstream::out | fstream::trunc fstream::in | fstream::out | fstream::trunc fstream::in | fstream::out | fstream::trunc in an open call (or constructor). Since the file does not exist yet, trimming the file with zero bytes is not a drama.

You will need an error when opening a file that does not exist when only ios::in specified, since you can never read from the stream, so it is better to start failing earlier.

+8
source share
 #include <fstream> ofstream out("test", ios::out); if(!out) { cout << "Error opening file.\n"; return 1; } ifstream in("test", ios::in); if(!in) { cout << "Error opening file.\n"; return 1; } 

If an error occurs, the message is displayed and one (1) is returned. However, only ofstream out("test", ios::out); can be compiled and executed ofstream out("test", ios::out); and ifstream in("test", ios::in); without any errors. In any case, a file is created.

+2
source share
 #include <iostream> #include <fstream> using namespace std; int main () { fstream f("test.txt", fstream::in | fstream::out); cout << f.fail() << endl; f << "hello" << endl; f.close(); return 0; } 

This code will print 1 and will not create the test.txt file if it does not exit. Therefore, it is not possible to open and run a file that does not exist without error.

0
source share
 std::fstream f("test.txt", std::ios_base::out); f.close(); //file now exists always f.open("test.txt", fstream::in | std::ios_base::out); //f is open for read and write without error 

I did not check that it opened without errors, but I am sure that it should.

0
source share

All Articles