Подтвердить что ты не робот

Как просмотреть файлы в каталоге в программе C?

Я пытаюсь написать ftp-сервер в Linux. В этом вопросе, как я могу перечислить файлы в каталоге на терминале программой C? Может быть, я могу использовать функцию exec для запуска команды find, но я хочу, чтобы имя файла было как строка для отправки клиентской программы. Как я могу это сделать?

Спасибо за ответы.

4b9b3361

Ответ 1

Пример, доступный для совместимых с POSIX систем:

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void)
{
  DIR           *d;
  struct dirent *dir;
  d = opendir(".");
  if (d)
  {
    while ((dir = readdir(d)) != NULL)
    {
      printf("%s\n", dir->d_name);
    }

    closedir(d);
  }

  return(0);
}

Остерегайтесь, что такая операция зависит от платформы в C.

Источник: http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

Ответ 2

Одно крошечное дополнение к JB Jansen answer - в основном цикле readdir() я бы добавил следующее:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Просто проверьте, действительно ли это файл, а не (sym) ссылка, каталог или что-то еще.

ПРИМЕЧАНИЕ: подробнее о struct dirent в libc документации.

Ответ 3

Вот полная программа для рекурсивного содержимого папки:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}