연습
find 프로그램 만들기.
JunkMam
2015. 5. 11. 17:23
fine 프로그램이란,
Linux에서 존재하는 find로 파일을 찾을때 사용한다.
현재 소스는 파일명을 찾는 소스가 아닌, 전체를 훍어서 전체 경로를 출력하는 소스이다.
만드는 방법으로, 재귀 함수를 이용한 백 트레킹이다.
나눠서 컴파일을 하는 분리 컴파일을 이용하였다.
파일명: dir.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> #include <stdlib.h> //디렉토리를 사용하기 위한 헤더파일 #include <dirent.h> //파일 정보를 받기 위한 파일. #include <sys/stat.h> //타이머설정. #include <windows.h> //잠시 일시 정지등을 하기 위한 파일. #include <conio.h> #ifndef __DIR_FIND_H__ #define __DIR_FIND_H__ int searchdir(const char*); #endif // __DIR_FIND_H__ | cs |
파일명: dir.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #include "_dir.h" /* searchdir parament : const char* str 수정하지 않는 str는 디렉토리 절대 경로로 이 경로 다음에 검색을 시작한다. */ int searchdir(const char* str){ DIR *dir=NULL;//디렉토리 연결 변수 struct dirent *dirs=NULL;//해당 디렉토리 파일명 변수 struct stat *status=NULL;//해당 디렉토리 파일 변수 char* tmpstr=NULL;//디렉토리 연결 변수. dir=opendir(str);//디렉토리 열어서 사용. dirs=readdir(dir);//.(현재 디렉토리 처리) dirs=readdir(dir);//..(이전 디렉토리 처리) //재귀 함수를 이용하여 디렉토리를 사용한다. while(dirs=readdir(dir)){ //파일 경로를 저장하기 위한 변수 할당. tmpstr=(char*)malloc(strlen(str)+dirs->d_namlen+3); //현재 디렉토리의 파일을 알아보기 위한 상태값을 받는 변수 할당. status=(struct stat*)malloc(sizeof(struct stat)); if(tmpstr==NULL){ printf("Errors"); exit(-1); } if(status==NULL){ printf("Errors Status"); exit(-1); } strcpy(tmpstr,str); strcat(tmpstr,dirs->d_name); stat(tmpstr,status); if(S_ISDIR(status->st_mode)){ strcat(tmpstr,"/"); printf("%s\n",tmpstr); Sleep(50); searchdir(tmpstr); }else{ printf("%s\n",tmpstr); Sleep(50); } free(status); free(tmpstr); } closedir(dir); return 0; } | cs |
파일명: main.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /** find 프로그램 해당 설정 경로에서 깊이 우선 순위로 파일을 찾아서 출력하는 목표. */ #include "dir/_dir.h" int main(int argc, char* argv[]) { if(argc >1){ printf("Find Start %s\n",argv[1]); printf("Press any key to start\n"); getch(); searchdir(argv[1]); }else{ printf("Find Start C:/\n"); printf("Press any key to start\n"); getch(); searchdir("C:/"); } return 0; } | cs |
find D:/을 넣을 경우
D: 드라이버에 폴더를 뒤지게 되어 있다.