I am using the following piece of code to check whether file is existing or not using std::ifstream
.
#include <iostream>
#include <fstream>
int main()
{
if (std::ifstream("file.txt"))
{
std::cout << "File present\n";
}
return 0;
}
Since I am not using any object for std::ifstream
, how do I close the file? Or is it not required to call close?
We can do that using the ifstream constructor. ifstream infile ("file-name"); The argument for this constructor is a string that contains the name of the file you want to open. The result is an object named infile that supports all the same operations as cin , including >> and getline .
New! Save questions or answers and organize your favorite content. Learn more.
Syntatically, this is done by adding a colon after the constructor name but before the brace, then listing the name of the field you want to initialize (here, myFile ), and then in parentheses the arguments you want to use to initialize it. This will cause myFile to be initialized properly. Hope this helps!
Actually you are using unnamed temporary object of std::ifstream
. It is not required to call std::ifstream::close()
, as the object is being destroyed after usage, and it's destructor closes the file correctly.
To be more precise:
// Temporary object is not yet created here
if (std::ifstream("file.txt"))
{
// Temporary object is already destroyed here
std::cout << "File present\n";
}
// Or here
From documentation:
(destructor)[virtual] (implicitly declared)
destructs the basic_ifstream and the associated buffer, closes the file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With