3

我在这里有一个非常基本的控制台程序,以确定文件夹或文件是否存在或不使用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

4 回答 4

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.
于 2010-12-14T01:29:50.383 回答
1

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

于 2010-12-14T01:26:35.340 回答
1

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

于 2010-12-14T01:27:02.870 回答
0

您可以通过检查找出stat()失败的原因(顺便说一下,这是一个 C 函数,而不是 C++)errno

#include <cerrno>

...

if (stat(path,&status) != 0)
{
    std::cout << "stat() failed:" << std::strerror(errno) << endl;
}
于 2010-12-14T01:40:22.087 回答