加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:31:18 所属栏目:百科 来源:网络整理
导读:我在这里有一个非常基本的控制台程序,使用stat确定文件夹或文件是否存在: #include iostream#include sys/stat.husing namespace std;int main() { char path[] = "myfolder/"; struct stat status; if(stat(path,status)==0) { cout "Folder found." endl;
我在这里有一个非常基本的控制台程序,使用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;
}

我也试过了访问版本:

#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进行编译,如果这有帮助的话.我相信这是一个快速解决方案 – 有人可以帮忙吗?

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

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

另一个更新

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

解决方法

在您的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读