0

I have the following C++ code as part of a larger program:

/* Open the output streams */
    std::ofstream outputFile;
    outputFile.open(outputName);
    std::ofstream outputFile1;
    outputFile1.open(outputName1);
    std::ofstream outputFile2;
    outputFile2.open(outputName2);

    std::cout <<  outputFile.is_open() << " " << outputFile1.is_open() << " " << outputFile2.is_open() << std::endl;
if (inputFile.is_open() && outputFile.is_open() && outputFile1.is_open() && 

outputFile2.is_open())
...

It's supposed to open several output file streams which will then - if they are all open - do a series of operations which writes to each one. However the program terminates early because the streams are never open:

0 0 0
Filestream or output streams could not open, ending program!

The variables outputName are std::strings, which I thought was allowed in C++11 (I have the -std flag enabled for C++11 in my OpenBlocks compiler options).

I'm not sure why the streams won't open.

Thanks.

SJWard
  • 3,629
  • 5
  • 39
  • 54
  • 2
    Have you checked the file names? – MartinStettner Aug 20 '14 at 15:07
  • 2
    How are we supposed to know why you can't access those files?! – Lightness Races in Orbit Aug 20 '14 at 15:11
  • _"The variables outputName are std::strings, which I thought was allowed in C++11"_ It is, and if that were the problem then you'd see a compilation error. – Lightness Races in Orbit Aug 20 '14 at 15:12
  • Apologies, I should add - the output files are not already extant - I expect the program to create them and then write to them, I was under the impression if a name used to open an ofstream does not correspond to an already existing file, a file of that name would be created. The name I'm using is simply "testout1.txt" "testout2.txt" and "testout3.txt". I (maybe incorrectly) assume that those files would be made in the current directory where I ran the executable. – SJWard Aug 20 '14 at 15:22
  • Just used 'if( !outputFile ) { std::cout << strerror(errno) << '\n'; }' in my code with the cerrno library and it says: No such file or directory! – SJWard Aug 20 '14 at 15:29

1 Answers1

6

File streams could fail to open for a number of reasons, such as if the path is invalid, if access is denied, or if the file is already open for writing in another program.

These errors are OS-dependent, and thus there is no standard way of reporting which one occured. However, you may be able to obtain an error code with the answers to this question.

If you're using Windows, be careful; if reports error code 5 (access denied) for all sorts of reasons that have nothing to do with permissions.

Community
  • 1
  • 1
IanPudney
  • 5,941
  • 1
  • 24
  • 39