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 님 감사드려요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.