2013-07-03 148 views
2

即时寻找代码将递归列出在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中的所有文件和目录。 >缓冲缓冲哪里包含什么程序应该打印到外壳

+2

呃...什么snprintf调用?代码片段中没有任何内容。如果你不明白它的作用,为什么不看看它做了什么? http://www.cplusplus.com/reference/cstdio/snprintf/ –

+2

sprintf到底有什么问题?它只是串联3个字符串 - 名称,“/”和entry_name。 –

+0

我认为sprintf正在创建所有问题 –

回答

0

sprintf(next, "%s/%s", name, entry_name); 

可以用

strcpy (next, name); 
strcat (next, "/"); 
strcat (next, entry_name); 

被取代,它会做同样的事情。这是否为你澄清?

+0

这是很快,是的,我现在感觉好多了,谢谢,是的,它是sprintf,对不起 – Saxtheowl

+1

请注意,每次调用'strcat()'都需要遍历整个字符串它的结尾,所以这里一个'sprintf()'调用更有效率。 –