Unix C程序以递归方式列出目录 [英] Unix c program to list directories recursively

查看:93
本文介绍了Unix C程序以递归方式列出目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行POSIX C学习练习,其中涉及递归地列出指定目录中的文件/文件夹.该程序接受一个或多个目录的参数.我可以列出初始目录的内容,但递归有问题.我为递归函数调用传递参数的方式有问题吗?

I am working on a POSIX C learning exercise that involves recursively listing files/folders in a specified directory. The program takes in as arguments of one or more directories. I can list the contents of the initial directory fine but having a problem with the recursion. Is something wrong with the way I am passing in the argument for the recursive function call?

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>

void listdir(char *argv[])
{
  DIR *mydirhandle;

  struct dirent *mydirent;

  struct stat statinfo;

  int n = 1;

  while(argv[n] != NULL)
  {
    if((mydirhandle = opendir(argv[n])) == NULL)
    {
      perror("opendir");
      exit(1);
    }

    printf("%s/\n", argv[n]);

    while((mydirent = readdir(mydirhandle)) != NULL)
    { 
      if((strcmp(mydirent->d_name, ".") == 0) || (strcmp(mydirent->d_name, "..") == 0))

      {
        continue;
      }

      else           
      {
        printf("\t%s\n", mydirent->d_name);

         //check if next entry is a directory       
         if(mydirent->d_type == DT_DIR)
        {   
             //is current directory being passed correctly here?
            listdir(mydirent->d_name);
        }
      }        
    }                       
    n++;
    closedir(mydirhandle);
  }
}
int main(int argc, char *argv[])
{
  if(argc < 2)
  {
    printf("usage: %s <directory>\n", argv[0]);
    return 0;
  }

  listdir(argv);
  return 0;
}

推荐答案

打开警告将显示您在进行递归函数调用时传递了错误的类型.我只需要让listdir接受一个char *参数而不是char **,然后在main中使用一个for循环就可以遍历多个参数.

Turning on warnings will show that you're passing the wrong type when making the recursive function call. I would simply make listdir take a char * argument rather than char **, and then use a for loop in main to loop over multiple arguments if you need to.

这篇关于Unix C程序以递归方式列出目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆