Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ifstream initialization with filename

Tags:

c++

ifstream

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?

like image 309
Arun Avatar asked Nov 18 '16 07:11

Arun


People also ask

How do I get an ifstream file name?

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 .

Does ifstream create a file?

New! Save questions or answers and organize your favorite content. Learn more.

How do you initialize fstream?

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!


1 Answers

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

like image 178
Sergey Avatar answered Oct 12 '22 12:10

Sergey