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?
In C++17 you have <filesystem>
in which you can do:
namespace fs = std::filesystem;
fs::path f{ "file.txt" };
if (fs::exists(f)) std::cout << "yes";
else std::cout << "nope";
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;
}
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