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_ui开发者_高级运维d, st.st_gid,
st.st_size, outstr, mydirent->d_name);
}
}
else
perror("stat ERROR: ");
closedir(mydir);
You need to concatenate the directory path and the file name.
stat(mydirent->d_name,&st) /* d_name is just the name, not the full path. */
Use s(n)printf
or something like that:
sprintf(fullpath, "%s/%s", dirpath, mydirent->d_name);
stat(fullpath, &st);
The problem is, as already stated by @cnicutar, that stat
wants the filename in the form dir/file
. The problems are:
- The
/
may not work on every operating system. - You need to allocate memory for the composed string, do overflow checks ...
If you don't insist on ANSI and can live with POSIX instead, then you can try fstatat
and dirfd
:
int dirfd(DIR *dirp); // convert DIR * from opendir() to dirhandle
int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags);
With fstatat
the pathname
is relative to the directory handle and you can point pathname
directly to struct dirent.d_name
.
精彩评论