가정하자 나는 파일 이름 /A/B/C/d.txt, 나는 역에서 디렉토리 경로를 인쇄 할파일 경로에서 반대 방향으로 디렉토리 경로를 얻으려면
을 가지고
/A/B/C/
/A/B/
/A/
다음은 재귀를 사용하여 디렉토리 경로를 역순으로 인쇄하는 프로그램입니다.
#include <stdio.h>
#include <libgen.h>
#include <string.h>
#include <stdlib.h>
void parsepath(const char *dirpath)
{
char* dirPathTemp;
char* dirname;
char path[255];
dirPathTemp = strdup(dirpath);
dirname = dirname(dirPathTemp);
strcpy(path, dirname);
free(dirPathTemp);
printf("path = %s\n", path);
if (0 != strcmp(path, "/"))
parsepath(path);
}
int main(int argc, char *argv[])
{
parsepath("/A/B/C/d.txt");
return 0;
}
재귀없이이 작업을 수행 할 수있는 다른 방법이 있습니까? 감사.
폭, cmon. 간단한 루프가 트릭을 수행합니다. 단순히 문자열 기능에 의존하는 대신 개별 문자를 선택하기 만하면됩니다. 경로를 통해 뒤로 작업하기 만하면됩니다. 덧붙여 말하자면,'strdup()'는 리눅스에서는 괜찮지 만 표준 C가 아닙니다. – Peter
힌트를 보내 주셔서 감사합니다. – Vicky