[C언어] Directory Scan / File or Directory
ITWeb/개발일반 2012. 5. 22. 23:33#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main (int argc, char *argv[]) {
DIR* dir;
struct dirent* entry = NULL;
struct stat statBuff;
char *path = "/home/jjeong/dist/simscan-1.4.0";
char buff[256]={'\0'};
if ( ( dir = opendir(path) ) == NULL) {
printf("Cannot Open Directory\n");
return -1;
}
while( ( entry = readdir( dir ) ) != NULL ) {
lstat(entry->d_name, &statBuff);
snprintf(buff, sizeof(buff), "%s/%s", path, entry->d_name);
//printf("Full Path :%s\n", buff);
if ( chdir(buff) == 0 ) {
printf("1.Directory : %s\n", entry->d_name);
} else {
printf("2.File : %s\n", entry->d_name);
}
/*
if ( S_ISDIR(statBuff.st_mode) ) {
if ( chdir(buff) == 0 ) {
printf("1.Directory : %s\n", entry->d_name);
} else {
printf("2.File : %s\n", entry->d_name);
}
} else if ( S_ISREG(statBuff.st_mode) ) {
printf("File : %s\n", entry->d_name);
}
*/
}
closedir(dir);
return 1;
}
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main (int argc, char *argv[]) {
DIR* dir;
struct dirent* entry = NULL;
struct stat statBuff;
char *path = "/home/jjeong/dist/simscan-1.4.0";
char buff[256]={'\0'};
if ( ( dir = opendir(path) ) == NULL) {
printf("Cannot Open Directory\n");
return -1;
}
while( ( entry = readdir( dir ) ) != NULL ) {
lstat(entry->d_name, &statBuff);
snprintf(buff, sizeof(buff), "%s/%s", path, entry->d_name);
//printf("Full Path :%s\n", buff);
if ( chdir(buff) == 0 ) {
printf("1.Directory : %s\n", entry->d_name);
} else {
printf("2.File : %s\n", entry->d_name);
}
/*
if ( S_ISDIR(statBuff.st_mode) ) {
if ( chdir(buff) == 0 ) {
printf("1.Directory : %s\n", entry->d_name);
} else {
printf("2.File : %s\n", entry->d_name);
}
} else if ( S_ISREG(statBuff.st_mode) ) {
printf("File : %s\n", entry->d_name);
}
*/
}
closedir(dir);
return 1;
}
원래 문서에 있는 데로 라면,
S_ISDIR 와 S_ISREG 에서 directory 와 file 이 구분되어져야 하는데.. 잘 되지 않았습니다.
그래서 workaround 로 chdir 의 result 값으로 directory 인지 file 인지 구분해 보았습니다. ㅡ.ㅡ;;