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

I have a fairly simple console program here to determine if a folder or file exists or not with 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 also tried the version access:

#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;
}

None of them find my folder (which is located directly in the same directory as the program). They worked on my last compiler (by default with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now if this helps. I'm sure this is a quick fix - can anyone help?

(Obviously, I am a noob, so if you need any other information that I forgot, let me know).

UPDATE

The problem was in the base directory. The updated work 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;
}

OTHER UPDATE

, .

+3
4

stat :

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

( ), . , , .

, , . IDE , .

, , .

, (gcc 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.
+5

, - , ? path , , .

+1

Check your PWD at startup of your program. This problem is not caused by the compiler. DevCpp can automatically set the working directory for your program.

+1
source

You can find out why stat()it failed (this is a C function, not C ++, by the way) by checking errno:

#include <cerrno>

...

if (stat(path,&status) != 0)
{
    std::cout << "stat() failed:" << std::strerror(errno) << endl;
}
0
source

Source: https://habr.com/ru/post/1780131/


All Articles