본문 바로가기
개발 업무(코딩)-개발자였을때 썼던..

c언어 리눅스(linux) 디렉토리 열기(opendir) & stat 간단 예제

by 주용사 2023. 1. 8.
728x90
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

int main()
{
        struct dirent *item;
        struct stat statbuf;
        DIR *dp;

        dp = opendir("/home/tqtlhj/han/"); // 경로 설정
        if (dp != NULL)
        {
                while(1)
                {
                        item = readdir(dp); // item에 디렉토리를 하나씩 넣어준다.
                        lstat(item->d_name, &statbuf); // 디렉토리인지 아닌지 체크하기 위한 stat
                        if (item == NULL)
                                break;
                        if(S_ISDIR(statbuf.st_mode)) // 디렉토리 일때만 출력
                                printf("DIR : %s\n", item->d_name);
                }
                closedir(dp);
        }
}

a.out 실행시

ls -al 명령어 실행시(d인것만 a.out에 출력됨)

728x90