模仿ansi C中的ls
我有一个代码可以模仿 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);
I have a code to mimic ls -la in ansi C, but when I change the directory from . (current directory) to any other it keep saying No such file or directory, any ideas why?
code:
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要连接目录路径和文件名。
使用 s(n)printf 或类似的东西:
You need to concatenate the directory path and the file name.
Use
s(n)printf
or something like that:问题是,正如@cnicutar 已经指出的那样,
stat
希望文件名的格式为dir/file
。问题是:/
可能无法在每个操作系统上工作。如果您不坚持使用 ANSI 并且可以使用 POSIX,那么您可以尝试
fstatat
和dirfd:
使用
fstatat
,pathname
是相对于目录句柄的,您可以将pathname
直接指向struct dirent.d_name.
The problem is, as already stated by @cnicutar, that
stat
wants the filename in the formdir/file
. The problems are:/
may not work on every operating system.If you don't insist on ANSI and can live with POSIX instead, then you can try
fstatat
anddirfd
:With
fstatat
thepathname
is relative to the directory handle and you can pointpathname
directly tostruct dirent.d_name
.