【发布时间】:2021-10-09 06:30:30
【问题描述】:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
// This program is going to scan all files in the current directory. It will make a tree for every folder
// and the folder will have a subsection of files in the tree format. YES SORTING!
char **word;
int coun = 0;
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name,&statbuf);
if (S_ISDIR(statbuf.st_mode)) // Check if it's a directory
{
/* Found a directory, but ignore . and .. */
if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
{
continue;
}
word[coun] = ("%s", entry->d_name); // Put the file name in the array.
coun++;
printf("- %*s%s\n", depth, "", entry->d_name); // Print the name of the dir entry.
/* Recurse at a new indent level */
printdir(entry->d_name, depth + 1);
}
else
{
word[coun] = ("%s", entry->d_name); // Put the file name in the array.
coun++;
printf("%*s - %s\n", depth, "", entry->d_name); // This will print the file.
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
word = calloc(1000, sizeof(*word));
printdir(".", 0);
printf("now, print the words in the order they were printed.\n");
for (int i = 0; i < coun; ++i)
{
printf("%s\n", word[i]);
}
exit(0);
}
我编写此代码的主要目的是创建目录中当前文件的树形结构。当我运行它时,我得到了这个输出。
- hw2
- tree
- Makefile
- ls.c
- tree.c
- find.c
- hw1
- grep.c
- factor.c
- uniq.c
- monster.c
- sort.c
- .nfs0000000006c543ea0000e073
- tree.c
- tree
now, print the words in the order they were printed.
hw2
grep.c
hw1
grep.c
factor.c
uniq.c
monster.c
sort.c
.nfs0000000006c543ea0000e073
tree.c
tree
树工作正常,但之后我仍然需要对文件进行排序。我的计划是将所有文件名放入全局单词数组中,然后区分文件夹和文件,并以相同的格式打印,但按字母顺序排序,不区分大小写。 我检查了数组,但 hw2 文件夹及其文件被完全覆盖。我不明白为什么会这样,因为它应该可以正常工作。 有谁知道解决方法或更好的方法吗?
【问题讨论】:
-
你试过debug代码吗?
标签: arrays c file tree metadata