即时寻找代码将递归列出在C编程参数给出的目录的所有目录和文件,我找到一个interresting代码(下),但我不明白snprintf函数,特别是“ /“, 我宁愿使用strcat或其他系统函数来覆盖sprintf函数,但我没有看到,因为我不明白snprintf在这里做什么。 继承人的代码:递归列出目录C
int is_directory_we_want_to_list(const char *parent, char *name) {
struct stat st_buf;
if (!strcmp(".", name) || !strcmp("..", name))
return 0;
char *path = alloca(strlen(name) + strlen(parent) + 2);
sprintf(path, "%s/%s", parent, name);
stat(path, &st_buf);
return S_ISDIR(st_buf.st_mode);
}
int list(const char *name) {
DIR *dir = opendir(name);
struct dirent *ent;
while (ent = readdir(dir)) {
char *entry_name = ent->d_name;
printf("%s\n", entry_name);
if (is_directory_we_want_to_list(name, entry_name)) {
// You can consider using alloca instead.
char *next = malloc(strlen(name) + strlen(entry_name) + 2);
sprintf(next, "%s/%s", name, entry_name);
list(next);
free(next);
}
}
closedir(dir);
}
从How to recursively list directories in C on LINUX
好了,我的程序正在运行,但现在我想保存打印到文件中像我跑我的程序./a.out中的所有文件和目录。 >缓冲缓冲哪里包含什么程序应该打印到外壳
呃...什么snprintf调用?代码片段中没有任何内容。如果你不明白它的作用,为什么不看看它做了什么? http://www.cplusplus.com/reference/cstdio/snprintf/ –
sprintf到底有什么问题?它只是串联3个字符串 - 名称,“/”和entry_name。 –
我认为sprintf正在创建所有问题 –