c/c++语言开发共享如何确定父/其他目录中的文件和目录

我发现这里的另一个问题的答案非常有用。

似乎有一个sys / stat.h库的限制,因为当我试图查看其他目录时,所有内容都被视为一个目录。

我想知道是否有人知道另一个系统function或为什么它将当前工作目录之外的任何内容视为仅一个目录。

我感谢任何人提供的任何帮助,因为这让我感到困惑,各种搜索都没有帮助。

我测试的代码是:

#include  #include  #include  int main(void) { int status; struct stat st_buf; struct dirent *dirInfo; DIR *selDir; selDir = opendir("../"); // ^ or wherever you want to look while ((dirInfo = readdir(selDir))) { status = stat (dirInfo->d_name, &st_buf); if (S_ISREG (st_buf.st_mode)) { printf ("%s is a regular file.n", dirInfo->d_name); } if (S_ISDIR (st_buf.st_mode)) { printf ("%s is a directory.n", dirInfo->d_name); } } return 0; } 

    您需要检查stat呼叫的状态; 它失败了。

    麻烦的是你在当前目录中找到一个文件the_file ,它实际上只能在../the_file找到。 readdir()函数为您提供相对于其他目录的名称,但stat()适用于当前目录。

    为了使它工作,你必须做相当于:

     char fullname[1024]; snprintf(fullname, sizeof(fullname), "%s/%s", "..", dirInfo->d_name); if (stat(fullname, &st_buf) == 0) ...report on success... else ...report on failure... 

    如果你打印出stat,你会发现有错误(找不到文件)。

    这是因为stat获取文件的路径,但您只是提供文件名。 然后,您可以在垃圾值上调用IS_REG。

    所以,假设你有一个文件../test.txt你在test.txt上调用stat …那不在目录./test.txt中,但你仍然打印出IS_REG的结果。

      以上就是c/c++开发分享如何确定父/其他目录中的文件和目录相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522244.html

      (0)
      上一篇 2020年12月9日
      下一篇 2020年12月9日

      精彩推荐