ifstream not creating and opening a file for output
-
03-07-2021 - |
Frage
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.
Lösung
The obvious problem is that you probably meant to open the file using a std::ofstream
rather than an std::ifstream
. This helps with actually writing to the stream although there are ways to write to an std::ifstream
as long as it is opened for reading. For example, you could use the std::streambuf
interface directly or use the std::streambuf
to construct and std::ostream
.
The more interesting question is: why isn't the file opened for writing when std::ios_base::in | std::ios_base::out
is used for the open mode? std::ifstream
automatically adds std::ios_base::in
. It turns out, that the mode std::ios_base::in | std::ios_base::out
doesn't create a file but it would successfully open an existing file. If you really want use an std::ifstream
to open a file for output which potentially doesn't exist you would need to use either std::ios_base::out | std::ios_base::trunc
or std::ios_base::out | std::ios_base::app
:
- the former would force the file to be created or truncated if it exists
- the latter would force writes to append to the file in all cases
My personal guess is, however, that you are best off just using std::ofstream
or, if you want to open the file for both reading and writing std::fstream
(which, however, would also need to have std::ios_base::trunc
or std::ios_base::app
added to create a file if none exists).
Andere Tipps
Declare the output file as an ofstream
rather than a ifstream
.
You could also use a fstream
for both input and output files.