Programing

C 프로그램의 디렉토리에있는 파일을 나열하는 방법은 무엇입니까?

lottogame 2020. 10. 7. 07:12
반응형

C 프로그램의 디렉토리에있는 파일을 나열하는 방법은 무엇입니까?


Linux에서 ftp 서버를 작성하려고합니다. 이 문제에서 C 프로그램으로 터미널의 디렉토리에있는 파일을 어떻게 나열 할 수 있습니까? 아마도 exec 함수를 사용하여 find 명령을 실행할 수 있지만 클라이언트 프로그램을 보낼 문자열로 파일 이름을 원합니다. 어떻게 할 수 있습니까?

답변 해 주셔서 감사합니다.


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


JB Jansen의 답변에 대한 작은 추가 사항 -메인 readdir()루프에 다음을 추가합니다.

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

(sym) 링크, 디렉토리 등이 아닌 파일인지 확인하십시오.

참고 :에 대한 자세한 struct dirent에서 libc문서 .


다음은 폴더의 내용을 재귀 적으로 나열하는 완전한 프로그램입니다.

#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);
}

아래 코드는 디렉토리 내의 파일 만 인쇄하고 순회하는 동안 지정된 디렉토리 내의 디렉토리를 제외합니다.

#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;
    char path[1000]="/home/joy/Downloads";
    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Condition to check regular file.
            if(dir->d_type==DT_REG){
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("%s\n",full_path);
            }
        }
        closedir(d);
    }
    return(0);     
}

참고 URL : https://stackoverflow.com/questions/4204666/how-to-list-files-in-a-directory-in-ac-program

반응형