簡體   English   中英

在ansi C中模仿ls

[英]Imitating ls in ansi C

我有一個代碼可以模擬ansi C中的ls -la ,但是當我從更改目錄時。 (當前目錄)對其他任何人都說“沒有這樣的文件或目錄,有什么想法嗎?”

碼:

DIR * mydir;
struct dirent * mydirent;
struct stat st;
char outstr[100];
struct tm *tmp;
mydir = opendir("..");
while ((mydirent=readdir(mydir))!=NULL)
  if ( stat(mydirent->d_name,&st) != -1 ) {
    tmp = localtime(&st.st_mtime);
    if (tmp == NULL)
      perror("localtime ERROR: ");
    else {
      strftime(outstr, sizeof(outstr), "%d/%m/%Y", tmp);
      printf("%o\t%d\t%d\t%d\t%d\t%s\t%s\n",
    st.st_mode, st.st_nlink, st.st_uid, st.st_gid, 
    st.st_size, outstr, mydirent->d_name);
    }
  } 
  else 
    perror("stat ERROR: ");
closedir(mydir);

您需要串聯目錄路徑和文件名。

stat(mydirent->d_name,&st) /* d_name is just the name, not the full path. */

使用s(n)printf或類似的東西:

sprintf(fullpath, "%s/%s", dirpath, mydirent->d_name);
stat(fullpath, &st);

問題是,正如@cnicutar所指出的那樣, stat希望文件名采用dir/file形式。 問題是:

  • /可能不適用於所有操作系統。
  • 您需要為組成的字符串分配內存,進行溢出檢查...

如果您不堅持使用ANSI而是可以使用POSIX,那么可以嘗試fstatatdirfd

int dirfd(DIR *dirp);    // convert DIR * from opendir() to dirhandle
int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags);

使用fstatatpathname是相對於目錄句柄的,您可以將pathname直接指向struct dirent.d_name

暫無
暫無

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

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