tags:

views:

189

answers:

3

Is it possible to open and fstream on a file that does not exist with both ios::in & ios::out with out getting error?

Thanks in advance.

A: 
#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 "test.txt" file, if it does not exit. So it is not possible to open and fstream on a file that does not exist without getting an error.

Draco Ater
Did you mean "filestr.fail()" and "filestr << "hello" << endl;"?!
Secko
@Secko Yes, thanks.
Draco Ater
A: 
#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 it is possible to compile and execute just ofstream out("test", ios::out); and ifstream in("test", ios::in); without any errors. Either way the file test is created.

Secko
+3  A: 

Update: To open an fstream on a file that does not exist for input and output (random access) without getting an error, you should provide fstream::in | fstream::out | fstream::trunc in the open (or constructor) call. Since the file does not already exist, truncating the file at zero bytes is no drama.

You would want an error when opening a file that doesn't exist when specifying only ios::in since you'll never be able to read from the stream so it's best to fail early.

Johnsyweb