初めてディレクトリを操作していて、いくつかの問題に直面しています。ディレクトリを探索し、ファイルサイズとアクセス許可を表示し、サブディレクトリを再帰する次の関数を作成しました。
void exploreDIR (DIR* dir, char cwd[], int tab)
{
struct dirent* ent;
while ((ent = readdir(dir)) != NULL)
{
if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
int i;
i = 0;
while(i < tab)
{
printf(" ");
i = i + 1;
}
printf("%s ", ent->d_name);
FILE *file = fopen(ent->d_name, "r");
int filesize;
if(file==NULL)
{
printf("[ Could not open! ]\n");
continue;
}
struct stat st;
stat(ent->d_name, &st);
filesize = st.st_size;
if (st.st_mode & S_IFDIR)
{
printf ("(subdirectory) [");
}
else
{
printf("(%d bytes) [", filesize);
}
printf( (S_ISDIR(st.st_mode)) ? "d" : "-");
printf( (st.st_mode & S_IRUSR) ? "r" : "-");
printf( (st.st_mode & S_IWUSR) ? "w" : "-");
printf( (st.st_mode & S_IXUSR) ? "x" : "-");
printf( (st.st_mode & S_IRGRP) ? "r" : "-");
printf( (st.st_mode & S_IWGRP) ? "w" : "-");
printf( (st.st_mode & S_IXGRP) ? "x" : "-");
printf( (st.st_mode & S_IROTH) ? "r" : "-");
printf( (st.st_mode & S_IWOTH) ? "w" : "-");
printf( (st.st_mode & S_IXOTH) ? "x" : "-");
printf("]\n");
fclose(file);
if (st.st_mode & S_IFDIR)
{
char tempwd[1024];
strcpy(tempwd, cwd);
strcat(tempwd, "/");
strcat(tempwd, ent->d_name);
DIR* tempdir;
if ((tempdir = opendir (tempwd)) != NULL)
{
printf("%s", tempwd);
exploreDIR(tempdir, tempwd, tab + 1);
}
}
}
closedir(dir);
}
ただし、関数がサブディレクトリで再帰する場合、fopen 関数は常に null を返します。私は私の人生のためにこれを理解することはできません。参考までに、主なものは次のとおりです。
int main(int argc, char** argv)
{
printf("\n");
DIR* dir;
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL)
{
if ((dir = opendir (cwd)) != NULL)
{
exploreDIR(dir, cwd, 0);
}
}
printf("\n");
return (EXIT_SUCCESS);
}
私は自分の方法論にもいくらか関心があります。strcat() は本当にサブディレクトリを探索する最良の方法ですか?
ありがとう