|
> このように一番最初のカレントディレクトリにあるsample3.c と dir4.c が
> 一番最後に表示されてしまいます。sample2.c と sample1.c はただしく表示
> されているのになぜこのふたつだけがこのように表示されてしまうのでしょうか?
カレントディレクトリにファイルとディレクトリを作るとき、
samplt1.c、sample2.c、ren2、dir4.c、sample3.c の順に作ったものと思われます。
readdir ではその順でファイル名を読み出しますから、このプログラムでは、ren2 の
下を表示した後、dir4.c、sample3.c を表示してしまいます。
この問題を解決するには、先にファイルを表示し、ディレクトリは後から表示
するようにすればよいでしょう。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void dirlist(char *dir)
{
struct dirent *entry; struct stat statbuf; char *tail;
DIR *dp;
printf("%s/\n", dir);
dp = opendir(dir);
if (dp == NULL) { perror("opendir"); return; }
tail = dir + strlen(dir);
*tail++ = '/';
while ((entry = readdir(dp)) != NULL) {
strcpy(tail, entry->d_name);
stat(dir, &statbuf);
if (!S_ISDIR(statbuf.st_mode)){
int n = strlen(entry->d_name);
if (n > 2 && strcmp(entry->d_name + n - 2, ".c") == 0)
printf(" %s\n", entry->d_name);
}
}
rewinddir(dp);
while ((entry = readdir(dp)) != NULL) {
if (strcmp(entry->d_name, ".") == 0) continue;
if (strcmp(entry->d_name, "..") == 0) continue;
strcpy(tail, entry->d_name);
stat(dir, &statbuf);
if (S_ISDIR(statbuf.st_mode)) dirlist(dir);
}
closedir(dp);
}
int main(int argc, char *argv[])
{
char dir[FILENAME_MAX];
strcpy(dir, argc < 2 ? "." : argv[1]);
dirlist(dir);
return 0;
}
|