C++ - stat(),access()在gnu gcc下无法正常工作

Ben*_*Ben 3 c c++ gcc stat

我在这里有一个非常基本的控制台程序,以确定文件夹或文件是否存在使用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;
}
Run Code Online (Sandbox Code Playgroud)

我也试过这个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;
}
Run Code Online (Sandbox Code Playgroud)

他们都找不到我的文件夹(它与程序在同一目录中).这些工作在我的上一个编译器(DevCpp的默认编译器)上.我切换到CodeBlocks,现在正在与Gnu GCC进行编译,如果这有帮助的话.我确定这是一个快速解决方案 - 有人可以帮忙吗?

(显然我是一个菜鸟,所以如果你需要我遗漏的任何其他信息,请告诉我).

UPDATE

问题出在基本目录中.更新的工作计划如下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

另一个更新

事实证明,路径上的尾随反斜杠是一个很大的麻烦.

pax*_*blo 5

stat通话之前,插入代码:

system("pwd");  // for UNIXy systems
system("cd");   // for Windowsy systems
Run Code Online (Sandbox Code Playgroud)

(或等效的)检查您当前的目录.我想你会发现它不是你的想法.

或者,从命令行运行可执行文件,在那里您知道您所在的目录.IDE将经常从您可能不期望的目录运行您的可执行文件.

或者,使用完整路径名,以便与您所在的目录无关.

对于它的价值,你的第一个代码段完美运行(在Ubuntu 10下的gcc):

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.
Run Code Online (Sandbox Code Playgroud)