There are two ways to create a file stream: you can create an empty file stream, open a file, and connect it to the stream later on; or you can open the file and connect it to a stream at construction time. These two procedures are demonstrated in the two following examples, respectively:
int main(int argc, char *argv[]) {
std::ifstream file; //1
// ...
file.open(argv[1]); //2
if (!file) // error: unable to open file for input
or:
int main(int argc, char *argv[]) {
std::ifstream file(argv[1]); //3
if (!file) // error: unable to open file for input
NOTE -- The traditional iostreams supported a constructor, taking a file descriptor, that allowed connection of a file stream to an already open file. This is not available in the standard iostreams. However, this implementation of the standard iostreams provides a corresponding extension. See Appendix B of the Apache C++ Standard Library Reference Guide for more information.
Generally you can check whether the attempt to open a file was successful by examining the stream state afterwards; failbit is set in case of failure.
There is also a member function called is_open() that indicates whether a file stream is connected to an open file. This function does not mean that a previous call to open() was successful. To understand the subtle difference, consider the case of a file stream that is already connected to a file. Any subsequent call to open() fails, but is_open() still returns true, as shown in the following code:
int main(int argc, char* argv[])
{
if (argc > 2) {
std::ofstream file; //1
file.open(argv[1]);
// ...
file.open(argv[2]); //2
if (file.fail()) //3
{ // open failed }
if (file.is_open()) //4
{ // connected to an open file }
}
}
In the example above, it would be advisable to close the file stream before you try to connect it to another file. This is done implicitly by the file streams destructor in the following code:
int main(int argc, char* argv[])
{
if (argc > 2) {
ofstream file(argv[2]);
// ...
} //1
if (argc > 1) {
ofstream file(argv[1]);
// ...
}
}
You can explicitly close the connected file. The file stream is then empty, until it is reconnected to another file:
int main(int argc, char* argv[])
{
std::ifstream f; //1
for (int i=1; i<argc; ++i) {
f.open(argv[i]); //2
if (f) { //3
// ... //4
f.close(); //5
}
else
std::cerr << "file " << argv[i] << " cannot be opened.\n";
}
}