在linux中实现ls -R命令

时间:2012-10-22 06:33:24

标签: c linux recursion

我想知道如何用C语言实现ls -R。 它是否使用递归算法?

5 个答案:

答案 0 :(得分:2)

这是相关的代码块

<includes...>
int f_recursive;        /* ls subdirectories also */
while ((ch = getopt(argc, argv, "1ABCFLRSTWabcdfghiklmnopqrstuwx")) != -1) {
    switch (ch) {
.
.
.
.
case 'R':
    f_recursive = 1;
    break;

稍后,由于上面的 int 标志,目录列表是递归完成的。

<强> See source here.

在您的情况下递归可能会导致堆栈溢出,如果您没有跳过目录...

尽管在ls.c内似乎没有进行任何递归。它使用 fts-functions ,就像fts_children一样遍历heirarchies。你可以使用相同的。

答案 1 :(得分:2)

为了完整起见,ls是GNU coreutils的一部分:www.gnu.org/software/coreutils /.

答案 2 :(得分:2)

“ls”(至少我所知的实现)使用fts_openfts_read ...来遍历文件层次结构。这些是“非递归”方法,它们在内部维护访问目录的列表。

使用“man fts_read”或http://linux.die.net/man/3/fts_read获取有关这些功能的更多信息。

答案 3 :(得分:2)

这是C中的简单linux ls -R实现。它提供类似于ls的彩色输出

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#define GREEN   "\x1b[32m"
#define BLUE    "\x1b[34m"
#define WHITE   "\x1b[37m"

void Usage() {
    fprintf(stderr, "\nUsage: exec [OPTION]... [DIR]...\n");
    fprintf(stderr, "List DIR's (directory) contents\n");
    fprintf(stderr, "\nOptions\n-R\tlist subdirectories recursively\n");
    return;
}

void RecDir(char *path, int flag) {
    DIR *dp = opendir(path);
    if(!dp) {
        perror(path);
        return;
    }
    struct dirent *ep;
    char newdir[512];
    printf(BLUE "\n%s :\n" WHITE, path);
    while((ep = readdir(dp)))
        if(strncmp(ep->d_name, ".", 1))
            printf(GREEN "\t%s\n" WHITE, ep->d_name);
    closedir(dp);
    dp = opendir(path);
    while((ep = readdir(dp))) if(strncmp(ep->d_name, ".", 1)) {
        if(flag && ep->d_type == 4) {
            sprintf(newdir, "%s/%s", path, ep->d_name);
            RecDir(newdir, 1);
        }
    }
    closedir(dp);
}

int main(int argc, char **argv)
{
    switch(argc) {
    case 2:
        if(strcmp(argv[1], "-R") == 0) Usage();
        else RecDir(argv[1], 0);
        break;
    case 3:
        if(strcmp(argv[1], "-R") == 0) RecDir(argv[2], 1);
        else Usage();
        break;
    default: Usage();
    }
    return 0;
}

答案 4 :(得分:1)

我认为这会对你有帮助。

 void listDir(char *dirName)
 {
     DIR* dir;
     struct dirent *dirEntry;
     struct stat inode;
     char name[1000];
     dir = opendir(dirName);
     if (dir == 0) {
        perror ("Eroare deschidere fisier");
        exit(1);
     }
     while ((dirEntry=readdir(dir)) != 0) {
        sprintf(name,"%s/%s",dirName,dirEntry->d_name); 
        lstat (name, &inode);

        // test the type of file
        if (S_ISDIR(inode.st_mode))
           printf("dir ");
        else if (S_ISREG(inode.st_mode))
           printf ("fis ");
        else
          if (S_ISLNK(inode.st_mode))
            printf ("lnk ");
        else;
          printf(" %s\n", dirEntry->d_name);
  }
相关问题