c - stat()不适用于父目录

标签 c directory parent stat

我正在尝试用 C 编写 ls 命令,但 stat() 拒绝打开任何其他目录。

 ~/Desktop/ls$ cat bug.c 
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <unistd.h>

int     main(int ac, char **av)
{
  DIR       *d;
  struct dirent *dir;
  struct stat   file;

  d = opendir(av[1]);
  if (d)
    {
      while ((dir = readdir(d)) != NULL)
        {
          printf("%s ->", dir->d_name);
          if (lstat(dir->d_name, &file) < 0)
          printf(" can't read file %s!", dir->d_name);
          printf("\n");
        }
    }
  closedir(d);
  return (0);
}

运行 ./a.out 时。或任何子文件夹,它工作正常。 但是如果我写 ./a.out .. ,它无法打开文件...

~/Desktop/ls$ ./a.out ..
.. ->
fkdkfdjkfdkfjdfkdfjkdfjkdjkfdkjf -> can't read file fkdkfdjkfdkfjdfkdfjkdfjkdjkfdkjf!
ss -> can't read file ss!
ls -> can't read file ls!
. ->
tg -> can't read file tg!

./a.out/home/login/Desktop 也不起作用,但是 ./a.out/home/login/Desktop/ls/ 显示正确当前文件夹的内容。

看起来 a.out 无法打开父目录,但是 ls -l 给出:

-rwxrwxr-x 1 hellomynameis hellomynameis 13360 nov.  25 09:56 a.out

我做错了吗?

谢谢!

最佳答案

您的 lstat 调用是错误的。当你从打开的目录中得到一个名称时,它是一个相对名称,所以你需要将其转换为正确的路径才能让 lstat 定位文件:

char path[...];
sprintf(path,"%s/%s",av[1],dir->d_name);
lstat(path,...);

关于c - stat()不适用于父目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33912482/

相关文章:

无法将 int 数字转换为数组(在 C 中)以输出接下来的 10 个八进制数字

version-control - 在 RCS 中使用文件夹

c# - 使用当前日期创建文件名

wpf - 从用户控件绑定(bind)到父用户控件的属性

javascript - iframe-在不指定域名的情况下更改父级的网址

在 Linux mint 中从 C 程序创建临时文件

c - C语言中如何区分int数组中的空和0?

C 如何制作消息列表?

linux - 无法进入 Gentoo Linux 中的文件系统目录

javascript - 如何在点击时删除父元素? - Angular JS