'programming/C_C++'에 해당되는 글 279건

  1. 2017.07.21 scandir

scandir

programming/C_C++ 2017. 7. 21. 18:34
반응형

 

/*** scandir ***/

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

#define DATA_FILE_DIRECTORY "."

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

    struct dirent **namelist;
    char sFullPathFileName[256] = {'\0'};

    int nFileCnt, nIdx;

    /*** 디렉토리 목록을 읽어 들인다 ***/
    nFileCnt = scandir(DATA_FILE_DIRECTORY, &namelist, 0, alphasort);

    if( nFileCnt > 0 ) {  /*** 파일카운트가 존재할때 ***/

        for( nIdx = 0; nIdx < nFileCnt; nIdx++ ) {  /*** for loop문 시작 ***/

            if( (strcmp(namelist[nIdx]->d_name, ".") != 0) && (strcmp(namelist[nIdx]->d_name, "..") != 0) ) {

                memset(sFullPathFileName, 0x00, sizeof(sFullPathFileName));
                sprintf(sFullPathFileName, "%s/%s", DATA_FILE_DIRECTORY, namelist[nIdx]->d_name);

                fprintf(stdout, "sFullPathFileName=%s\n", sFullPathFileName);

            }

            free(namelist[nIdx]);

        }  /*** for loop 문 끝 ***/

        free(namelist);

    }  /*** 파일카운트가 존재할때 ***/

    return 1;

}

 

 

/*** opendir,  readdir ***/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>

#define sDirPath "./"

int main(int artc, char *argv[])
{

    DIR*            dirp;
    struct dirent*  dp;

    if ((dirp = opendir(sDirPath)) == NULL) {

        fprintf(stdout,"opendir(). Failed. sDirPath[%s] errno=%d(%s)\n", sDirPath, errno, strerror(errno));

        return -1;

    }
    else {

        while ( ( dp = readdir( dirp ) ) != NULL ) {

            if( strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0 ) {

                fprintf(stdout, "%s\n", dp->d_name);

            }

        }

    }

    closedir(dirp);

    return 1;

}

 

반응형
Posted by 공간사랑
,