[英]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,那么可以嘗試fstatat
和dirfd
:
int dirfd(DIR *dirp); // convert DIR * from opendir() to dirhandle
int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags);
使用fstatat
, pathname
是相對於目錄句柄的,您可以將pathname
直接指向struct dirent.d_name
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.