stat() 不适用于父目录

rap*_*777 0 c directory parent stat

我正在尝试ls用 C编写命令,但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);
}
Run Code Online (Sandbox Code Playgroud)

运行时./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!
Run Code Online (Sandbox Code Playgroud)

./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
Run Code Online (Sandbox Code Playgroud)

我做错了吗?

谢谢 !

Jea*_*nès 5

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

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