get info on a file without opening it from C/C++

April 6, 2009

If you need to get info about a file without opening it, you can use <sys/stat.h> to do so.

I needed a way to test the existence of a file. Version 1 called fopen and tested for NULL, but this also meant some nasty ifs and fclose logic.

Here’s the better way:


#include <iostream>
#include <cerrno>
#include <sys/stat.h>
struct stat fileInfo;
const char* filename = "myFile";
if(stat(filename, &fileInfo) != 0){ //error
  if(errno == ENOENT){
    std::cerr << "File " << myFile << " doesn't exist" << std::endl;
  else{ //any other error
    std::cerr << "Error getting info on file " << filename << ": "
              << strerror(errno) << std::endl;
  }
}

File existence is but one of the few things you check for.  Just be careful what you check for though, as many of the attributes in struct stat are Unix only.

See stat()’s documentation for more details.

Leave a Reply