C++ - stat(), access() not working under gnu gcc

Ben picture Ben · Dec 14, 2010 · Viewed 7.8k times · Source

I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

I have also tried the access version:

#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

Neither of them find my folder (which is right there in the same directory as the program). These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps. I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory. The updated, working program is as follows:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

Answer

paxdiablo picture paxdiablo · Dec 14, 2010

Right before your stat call, insert the code:

system("pwd");  // for UNIXy systems
system("cd");   // for Windowsy systems

(or equivalent) to check your current directory. I think you'll find it's not what you think.

Alternatively, run the executable from the command line where you know what directory you're in. IDEs will frequently run your executable from a directory you may not expect.

Or, use the full path name so that it doesn't matter which directory you're in.

For what it's worth, your first code segment works perfectly (gcc under Ubuntu 10):

pax$ ls my*
ls: cannot access my*: No such file or directory

pax$ ./qq
Cannot find folder.

pax$ mkdir myfolder

pax$ ll -d my*
drwxr-xr-x 2 pax pax 4096 2010-12-14 09:33 myfolder/

pax$ ./qq
Folder found.