10

I want to determine if a file exists in C++ 11

I have the following codes:

ifstream inputFile(c);

if (!inputFile.good()) {
        std::cout << "No file found" << '\n';           
}

And

if (inputFile.peek() == std::ifstream::traits_type::eof()){
           ....
}

Which one is correct and idiomatic?

6
  • 1
    What version (c++11, c++14, ...) of C++ are you using? The suggested / "most idiomatic" solutions may differ based on that. Commented Nov 24, 2019 at 21:56
  • @druckernamly edited, c++ 11 Commented Nov 24, 2019 at 21:57
  • Just mentioning: if you have access to C++17, then std::filesystem::exists is there. Commented Nov 24, 2019 at 22:02
  • I guess your intent is to check whether the file is readable or not by your process. It is a bit different from just testing if this file exists; it could exist but your process may not be able to read its content (permissions...). Commented Nov 24, 2019 at 22:03
  • The first one looks better to me. Why check if an arbitrary file-related function returns an error, if you can directly check if the file was opened correctly. Commented Nov 24, 2019 at 22:04

2 Answers 2

12

In C++17 you have <filesystem> with which you can do:

namespace fs = std::filesystem;
fs::path f{ "file.txt" };
if (fs::exists(f)) std::cout << "yes";
else               std::cout << "nope";
Sign up to request clarification or add additional context in comments.

1 Comment

Might be worth noting that even if the file exists, then it may not be possible to open it or read or write it. It may also be deleted by some other process an instant after the check returns true.
3

If you're trying to determine if a file exist using C++11 you may want to try this idea

#include <iostream>
#include <fstream>

int main(int argc, char *argv[]){
    std::ifstream file("myfile.txt");
    if(!file.is_open()){
        std::cout << "File not found" << std::endl;
        return -1;
    }

    return 0;
}

6 Comments

try this with "/etc/shadow" or "/etc/sudoers" ;^)
Although this is just a common solution, if you're not specific in your solution
okay i will try that
the std::basic_ios<CharT,Traits>::good returns true when the IO operation was done most recently, and may not be the right or proper solution. Except you have something in mind to achieve and maybe the question wasn't properly asked.
It's not really important, just a matter of vocabulary. I think that the fact that a file exists or not is different from the fact that this file is readable or not. Your example tests if the file is readable and if it fails it concludes that this file is not found. It may be actually found but not readable (due to permissions) by your process. So I would say that this file is not "readable". (no big deal...)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.