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

时间:2010-12-14 01:20:29

标签: 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;
}

我也尝试了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;
}

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

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

更新

问题在于基目录。更新的工作计划如下:

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

另一个更新

原来,路径上的尾随反斜杠很麻烦。

4 个答案:

答案 0 :(得分:5)

stat电话会议之前,插入代码:

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

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

或者,从您知道您所在目录的命令行运行可执行文件.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.

答案 1 :(得分:1)

您确定正在运行的程序的当前目录是您期望的吗?尝试将path更改为绝对路径名,看看是否有帮助。

答案 2 :(得分:1)

运行程序时检查您的PWD。此问题不是由编译器引起的。您DevCpp可以自动为您的程序设置工作目录。

答案 3 :(得分:0)

通过检查stat()

,您可以找出errno失败的原因(顺便说一句是C函数,而不是C ++)
#include <cerrno>

...

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