tags:

views:

83

answers:

3
#include <iostream>
#include <fstream>
#include <cstdlib>

int main() {
    std::fstream f1("/tmp/test");
    if (!f1) {
        std::cerr << "f1 failed\n";
    } else {
        std::cerr << "f1 success\n";
    }
    FILE *f2 = fopen("/tmp/test", "w+");
    if (!f2) {
        std::cerr << "f2 failed\n";
    } else {
        std::cerr << "f2 success\n";
    }
}

Creating a file in /tmp/ doesn't work for me using fstreams but it does with fopen. What could be the problem? (I get f1 failed and f2 success when /tmp/test doesn't already exist)

+5  A: 

You have to tell the fstream you are opening the file for output, like this

std::fstream fs("/tmp/test", std::ios::out);

Or use ofstream instead of fstream, that opens the file for output by default:

std::ofstream fs("/tmp/test");
Thomas
http://www.cplusplus.com/reference/iostream/fstream/fstream/ says the default constructor for fstream already sets ios_base::out, so why doesn't it work as originally written?
Steven
I guess plain fstream fails because it also adds ios::in, and the file has to exist when opening for input.
Thomas
Because `in|out` doesn't create the file if it doesn't exist. `in|out|trunc`, `out|trunc`, `out|app`, and `out` values for openmode will create it.
Roger Pate
Using just out by itself still manages to create the file if it doesn't exist on my system. I guess this isn't reliable behavior?
Steven
It is reliable, the issue is that fstream defaults to in|out (which will *not* create the file), while ofstream defaults to just out (which will create the file).
Roger Pate
Ah, sorry I missed that part in your comment.
Steven
A: 

Your first method call does not automatically create a file: see fstream.

If you want your first method call to create a file, use:

std::fstream f1("/tmp/test", fstream::out);
Chip Uni
A: 

I don't know which is the default mode for the fstream constructor, I tried with this and it worked

std::fstream f1("/tmp/test", std::fstream::in | std::fstream::out);

It creates a file for input and output, you should check the fstream documentation here

Ismael