lstat() 을 이용, 디렉토리 구분이 안되요.

tius1234의 이미지

안녕하세요. C언어 초보 김군입니다.

이번에, 디렉토리를 검색하여, 파일명 및 디렉토리명을 조회하는 함수를 만들려고 하는데요,
이상하게 파일도, 디렉토리로 구분을 합니다.

S_ISREG(buf.st_mode) 이 부분을 실행시, 파일 또한 디렉토리로 구분을 하는데,
제가 뭘 잘 못한건지... 구분이 안되고 다 디렉토리로 됩니다.

#include
#include
#include
#include
#include

int main()
{
// 이통사|증권사|은행|서비스|플랫폼|해상도

DIR* dp = NULL;
struct dirent* entry = NULL;
struct stat buf;

if((dp = opendir("/user/nis/nis/source/exmobile/240/img")) == NULL)
{
printf("/user/nis/nis/source/exmobile/240/img 를 열수 없습니다...\n");
return -1;
}

while ((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name, &buf);

if(S_ISREG(buf.st_mode))
{
printf("[파일이름] %s\n", entry->d_name);
}
else if(S_ISDIR(buf.st_mode))
{
printf("[디렉토리이름] %s\n", entry->d_name);
}

}

closedir(dp);

return 0;
}

도움 부탁 드립니다.

mach의 이미지

1) lstat()의 리턴값을 검사한다.
주의사항 : 실행디렉터리와 검사하고자 하는 데이터 디렉터리가 틀린경우 전체경로(full path)를 주는 습관을 갖는다.
위의 경우 "/user/nis/nis/source/exmobile/240/img" 디렉터리를 열고, 실행은 다른 디렉터리에서 할것이다.
예를 들어, "/user/nis/nis/source/exmobile/240/img/XXX"라는 파일이 있는 경우,
lstat(entry->d_name, &buf);// 이런 식으로 호출하면,
실제로는
lstat("XXX", &buf);// 이런 식으로 처리될 것이며,
해당 파일을 찾지 못하여, lstat()의 리턴값이 -1로 나오게 될것이다.
2) 파일이나 디렉터리 처리시에는 풀패쓰를 주는 습관을 갖는다.

이상은 그냥 관습을 기술했습니다.
테스트 프로그램은 아래와 같겠습니다.

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
 
 
int main(int argc, char **argv)
{
    char *path;
    struct stat stat_p;
    int err;
    DIR *srcdir;
    struct dirent *pent;
    char fileName[4096];
 
    if (argc < 2 ) {
        printf("./a.out <dirname>\n");
        exit(0);
    }
    path = argv[1];
 
    srcdir = opendir(path);
    while(( pent = readdir(srcdir)) != NULL) {
        snprintf(fileName, 4096, "%s/%s", path, pent->d_name);
        printf("filename '%s' ==>", fileName);
        //err = lstat(fileName, &stat_p);
        err = lstat(pent->d_name, &stat_p);
 
 
        if ( err == -1 ) {
            printf("err = %d : %d : %s\n", err, errno, strerror(errno));
        }
        else {
            if ( S_ISREG(stat_p.st_mode) ) {
                printf("reg!\n");
            }
            else if ( S_ISDIR(stat_p.st_mode) ) {
                printf("dir\n");
            }
            else {
                printf("other\n");
            }
        }
    }
    return 0;
}

------------------ P.S. --------------
지식은 오픈해서 검증받아야 산지식이된다고 동네 아저씨가 그러더라.

------------------ P.S. --------------
지식은 오픈해서 검증받아야 산지식이된다고 동네 아저씨가 그러더라.

익명 사용자의 이미지

sprintf(fullpath,"%s/%s","/home/dir1/dir2",pent->d_name);
lstat(fullpath, &buf);

....

이런 식으로 해결했습니다. 작동이 잘 되네요.

mach 님 감사드려요.