How to check if file exisits

closed account (17poGNh0)
How do I check if a file already exists using C++??? Plz send me the codez.
Using OS specific functions would be more efficient and safer, but with "pure" C++ you can't do better than JL's version as C++ doesn't actually have the concept of a file system.
This would actually be a wee bit more efficient:

1
2
3
4
5
6
7
8
std::filebuf fbuf ;
fbuf.open( "whatever", std::ios::in | std::ios::binary ) ;

if( !fbuf.is_open() )
      std::cerr << "couldn't open file\n" ;

else if( fbuf.snextc() == std::filebuf::traits_type::eof() )
      std::cout << "the file is empty\n" ;


But then, it does not really matter. Checking if a file exists / is empty is typically done once per file, right at the beginning - unlike i/o which would be in a loop.
The boost library has a function for that, boost::filesystem::exists() http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/reference.html#exists The boost.filesystem library is planned for inclusion in C++ at the next revision and Visual studio already includes that part of boost in its standard library
Topic archived. No new replies allowed.