I am developing in C++ using NetBeans 6.9 on Ubuntu 11.04. I have declared the input and output file name strings and file streams thus
ifstream fpInputFile, fpOutputFile;
string inputFileName="", outputFileName="";
The input file name is assigned the name of an existing file as an input argument to the application. The output file name is given the same as the input name except that “_output” is inserted before the final period. So the output is written to the same directory as the input is located. Also I start netbeans with
su netbeans
so the IDE has root privileges to the directory. I try to open the files, and check whether they are opened thus.
fpInputFile.open(inputFileName.c_str(), ifstream::in);
fpOutputFile.open(outputFileName.c_str(), ifstream::out);
if (!(fpInputFile.is_open())) throw ERROR_OPENING_FILE;
if (!(fpOutputFile.is_open())) throw ERROR_OPENING_FILE;
The input file opens successfully but the output file does not.
Any help in determining why the output file is not opening for writing would be most appreciated.
The obvious problem is that you probably meant to open the file using a
std::ofstreamrather than anstd::ifstream. This helps with actually writing to the stream although there are ways to write to anstd::ifstreamas long as it is opened for reading. For example, you could use thestd::streambufinterface directly or use thestd::streambufto construct andstd::ostream.The more interesting question is: why isn’t the file opened for writing when
std::ios_base::in | std::ios_base::outis used for the open mode?std::ifstreamautomatically addsstd::ios_base::in. It turns out, that the modestd::ios_base::in | std::ios_base::outdoesn’t create a file but it would successfully open an existing file. If you really want use anstd::ifstreamto open a file for output which potentially doesn’t exist you would need to use eitherstd::ios_base::out | std::ios_base::truncorstd::ios_base::out | std::ios_base::app:My personal guess is, however, that you are best off just using
std::ofstreamor, if you want to open the file for both reading and writingstd::fstream(which, however, would also need to havestd::ios_base::truncorstd::ios_base::appadded to create a file if none exists).