시스템 프로그래밍 디렉토리 탐색 소스인데요.
#include
#include
#include
#include
#include
#include
void printdir(char *dir, int depth)
{
DIR *dp; // 디렉토리 포인터
struct dirent *entry; // 디렉토리에 하나의 엔트리 정보만 읽어들임.
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr, "cannot open directory: %s\n", dir);
return;
}
chdir(dir); // 지정된 작업디렉토리로 이동.
while((entry = readdir(dp)) != NULL) {
// 디렉토리 항목에서 파일 이름을 가져온 뒤 statbuf가 가리키는 구조체에 저장한다.
lstat(entry->d_name, &statbuf);
if(S_ISDIR(statbuf.st_mode)) { // 파일 종류가 디렉토리이면
// 디렉토리를 찾았음. .와 ..는 무시한다
if(strcmp(".", entry->d_name) == 0 ||
strcmp("..", entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth, "", entry->d_name);
// 새로운 들여쓰기 수준을 지정해서 재귀 호출
printdir(entry->d_name, depth+4);
}
else
// 디렉토리의 내용을 출력
printf("%*s%s\n", depth, "", entry->d_name);
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir = "."; // 탐색하고자 하는 디렉토리를 지정하지 않으면 현재 디렉토리를 기준으로 한다.
if(argc >= 2)
topdir=argv[1];
printf("Directory scanf of %s\n", topdir);
printdir(topdir, 0);
printf("done.\n");
}
위 소스에서 printdir() 함수를 호출할 때 찾고자 하는 디렉토리와 재귀 호출을 할 때 들여쓰기의 크기를
인자로 전달하는 건 알겠는데, while()루프 안에 printf("%*s%s/\n",depth, "", entry->d_name); 부분에서
"%*s%s/" 중에 %*s 의미를 모르겠네요. 그리고 depth 인수는 어떤 서식지정자와 매칭되나요?
참고하세요.. One can also specify
참고하세요..
One can also specify explicitly which argument is taken, at each place where an argument is required, by writing
"%m$" instead of '%' and "*m$" instead of '*', where the decimal integer m denotes the position in the argument list of the desired argument, indexed starting from 1. Thus,
printf("%*d", width, num);
and
printf("%2$*1$d", width, num);
are equivalent.
오늘도 생명과 호흡을 주심에 감사합니다.
댓글 달기