簡體   English   中英

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

[英]stat() doesn't work on parent 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);
}

運行./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,...);

程序a.out可能無權讀取該文件夾中的所有文件。 嘗試以root權限運行a.out。

並且,如果要檢查錯誤,請在lstat函數無法成功執行時打印errno以獲取錯誤的詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM