Search code examples
c++file-handlingfstream

Trouble opening an fstream file in c++ (Newbie)


I'm learning about file handling in C++ and in the part explaining how to open a file it had this:

ifstream fin( "inputFile.txt" );

or this:

ifstream fin;
fin.open( "inputFile.txt" );

My first question is: What does inputFile.txt do here?

  • Is it simply the name of the file I open?
  • If so, what is the role of .txt? I've also seen .bin used in its place too.
  • Since the function's syntax is open (filename, mode) and inputFile.txt is passed in the filename paramater, why can't we just put a string there without the .txt?

I also encountered another problem. When I write this command in visual studio using the fail() function, it appears the file doesn't open properly as it sends the Error - Failed to open message

int main() {
    std::ifstream fin("inputFile.txt"); //open file
    if (fin.fail()) {                   //check if opened properly
        std::cerr << "Error - Failed to open ";
    }
    else { std::cout << "Opened properly"; 
    }
    return 0;
}

Outputs : Error - Failed to open

The only case I've noticed it doesn't have a problem is when I pass filename.txt as an argument

int main() {
    std::ifstream fin("filename.txt"); //open file
    if (fin.fail()) {                  //check if opened properly
        std::cerr << "Error - Failed to open ";
    }
    else { std::cout << "Opened properly"; 
    }
    return 0;
}

Outputs : Opened properly

Why is that? In the instructions it had inputFile.txt and it doesn't work here. Also, why does it even matter if it's inputFile.txt or filename.txt, isn't it just a name?

Sorry for the number of questions, I'm just really confused over this and would really appreciate it if someone could clear this all up for me.


Solution

  • What does inputFile.txt do here?

    inputFile.txt allows (in this case) fin to determine what file it’s opening, so yes, it is the name of the file you open.

    The role of .txt is the same as the entire file name. For example, if you had 2 inputFile files, one being .txt and one being .bin, you would use the file extension to differentiate which one you’re opening.

    If I’m not mistaken, C++ won’t be able to find the file you’re trying to open without the file extension.

    fail() function

    Try using is_open() instead of fail(). fail() is better for reading/writing status, rather than checking for opening errors. is_open() will return a boolean for whether or not the file was successfully opened.

    My guess for why filename.txt works but inputFile.txt doesn’t is because fail is not returning reading or writing errors because the file “filename.txt” doesn’t exist.

    Hope this helps!

    (Source: https://cplusplus.com/reference/ios/ios/fail/)