Use of `ofstream` appears not to create nor write to file

ely picture ely · Apr 4, 2012 · Viewed 18.6k times · Source

At the end of a simulation, I want to write some results as an appended row to a data file. The code I am using is the following, where you can assume that outFile was correctly allocated as an std::ofstream, that output_file is a std::string containing a valid path to a file that does not yet exist, and that the variables printed out to the file are just int types that get values during the simulation.

outFile.open(output_file.c_str(), std::ios::out | std::ios::app );
outFile << num_nodes << ", " << tot_s << ", " << tot_c << ", " << tot_d << std::endl;
outFile.close();

I've checked whether it correctly opens the file with the ofstream::is_open() function and it returns false. However, I can't figure out why. I've tried it with many different file names and directory paths, all of which I have checked and they are valid (no typos, etc.)

The file being written is just into a folder on the desktop where I create files all the time, so I don't see how it could be a permissions issue. If it was a permissions issue, how can I check that?

Otherwise, what else can be preventing it from writing to the file?

Added:

Following up on the comments, after adding a call to perror(), it is displaying the "No such file or directory" error. The file path in question is:

/home/ely/Desktop/Evolutionary_Dynamics/GamesOnCycle/data/test.data

I want this file to be created, and all the directories in that path exist, it's all spelled correctly, etc., and there are no weird permission issues with the GamesOnCycle folder or its data subfolder. Note that it is a linux system (Ubuntu 11.04) so the forward slashes are correct for the file path, unless I'm missing something that C++ has to have w.r.t. file paths.

Answer

josephthomas picture josephthomas · Apr 4, 2012

This could be happening due to several reasons.

1) The file is already open.

2) All the directories in the file path are not created.

3) Lack of file permissions.

For an additional reference, please see When will ofstream::open fail?