我正在尝试用 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/