【发布时间】:2013-07-01 11:50:20
【问题描述】:
我正在寻找一个代码,该代码将递归列出 C 编程中参数给出的目录的所有目录和文件,我找到了一个有趣的代码(如下),但我不了解 snprintf 函数,特别是“/”, 我更喜欢使用 strcat 或其他系统函数来覆盖 sprintf 函数,但我不明白如何,因为我不明白 snprintf 在这里做什么。 代码如下:
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 一样。 > 缓冲区,其中缓冲区包含程序应在 shell 上打印的内容
【问题讨论】:
-
呃... snprintf 叫什么?代码 sn-p 中没有。如果您不了解它的作用,为什么不查找它的作用? cplusplus.com/reference/cstdio/snprintf
-
您的 sprintf 到底有什么问题?它只是连接 3 个字符串 - 名称、“/”和 entry_name。
-
我认为 sprintf 正在制造所有问题
标签: c