2009-07-19 5 views
21

C++에서 모든 파일/하위 디렉터리 (재귀 삭제)가있는 폴더를 삭제하려면 어떻게해야합니까?폴더 및 모든 파일/하위 디렉터리 삭제

+0

그냥 측면 노드 :이 질문에 중복이 있습니다, 당신이 부스트에 의존하고 싶지 않다면, 그것은 인정 대답 [봐주는 가치가있다] (http://stackoverflow.com/a)/2256974/1312382). – Aconcagua

답변

1

표준 C++은이를 수행 할 방법이 없습니다. 운영 체제 특정 코드 또는 Boost와 같은 교차 플랫폼 라이브러리를 사용해야합니다.

18

:

system("rm -rf /path/to/directory") 

아마도 더 당신이 찾고 있지만, 유닉스 특정하는지 :

/* Implement system("rm -rf") */ 

#include <stdlib.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <sys/syslimits.h> 
#include <ftw.h> 


/* Call unlink or rmdir on the path, as appropriate. */ 
int 
rm(const char *path, const struct stat *s, int flag, struct FTW *f) 
{ 
    int status; 
    int (*rm_func)(const char *); 

    switch(flag) { 
    default:  rm_func = unlink; break; 
    case FTW_DP: rm_func = rmdir; 
    } 
    if(status = rm_func(path), status != 0) 
     perror(path); 
    else 
     puts(path); 
    return status; 
} 


int 
main(int argc, char **argv) 
{ 
    while(*++argv) { 
     if(nftw(*argv, rm, OPEN_MAX, FTW_DEPTH)) { 
      perror(*argv); 
      return EXIT_FAILURE; 
     } 
    } 
    return EXIT_SUCCESS; 
} 
+10

downvoter의 플랫폼에 nftw가 없기 때문에 C++ 대신 C가 있기 때문에 downvoted 되었습니까? (g ++ -Wall -Wextra로 잘 컴파일되었지만)? downvote 때 제발, 제발! 이것은 견고한 코드입니다. –

+0

'system ("rm -rf/path/to/directory")'는 어떻게 이식 가능합니까? * nix OS에서 작동합니까? Windows에서는 분명히 작동하지 않습니다. –

4

당신은 파일을 디렉토리를 탐색 및 삭제, readdir(), nftw(), ftw()readdir_r()을 사용할 수 있습니다 재귀 적으로.
그러나 ftw(), nftw(), readdir()은 스레드로부터 안전하지 않으므로 프로그램이 멀티 스레드 환경에서 실행되는 경우 대신 readdir_r()을 권장합니다.

관련 문제