简体   繁体   English

stat()在父目录上不起作用

[英]stat() doesn't work on parent directory

I'm trying to code the ls command in C, but stat() refuse to open any other directory. 我正在尝试在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);
}

When running ./a.out . 运行./a.out or any subfolder, it works correctly. 或任何子文件夹,它可以正常工作。 But if I write ./a.out .. , it fails to open files... 但是如果我写./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 doesn't work either, but ./a.out /home/login/Desktop/ls/ display correctly the content of the current folder. ./a.out /home/login/Desktop也不起作用,但是./a.out /home/login/Desktop/ls/正确显示当前文件夹的内容。

It looks like a.out can't open parents dir, but ls -l gives : 看起来a.out无法打开父目录,但ls -l给出了:

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

Am I doing it the wrong way ? 我做错了吗?

Thanks ! 谢谢 !

Your lstat call is wrong. 您的lstat呼叫有误。 When you get a name from the opened directory, it is a relative name, so you need to convert it to a correct path to let lstat locate the file: 从打开的目录中获取名称时,它是一个相对名称,因此您需要将其转换为正确的路径,以便lstat定位文件:

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

The program a.out may has not permission to read all the files in that folder. 程序a.out可能无权读取该文件夹中的所有文件。 Try to run a.out with root permission. 尝试以root权限运行a.out。

And, if you want to check the error, please print the errno to get the detail of error when the lstat function does not execute success. 并且,如果要检查错误,请在lstat函数无法成功执行时打印errno以获取错误的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM