BLOG ARTICLE NSFileManager | 2 ARTICLE FOUND

  1. 2008.04.01 NSFileManager를 이용한 디렉토리, 파일 복사/이동/삭제
  2. 2008.03.13 파일 목록 및 속성 구하기

NSFileManager로 파일과 디텍토리를 복사/이동/삭제하는 간단한 예제 소스입니다. 각 단계는 enter를 로그창에 입력하면 진행되면 아래와 같은 순서로 작업을 합니다.

  1. test 디렉토리 생성
  2. test 디렉토리를 test2로 변경
  3. test.txt 파일을 test2 디렉토리 아래에 new_test.txt로 복사
  4. test2 디렉토리로 이동
  5. new_test.txt를 re_test.txt로 변경
  6. re_test.txt 삭제
  7. 상위 디렉토리로 이동
  8. test2 디렉토리 삭제
테스트 전에 실행파일이 있는 디렉토리에 test.txt란 파일을 vi나 편집기를 이용해 만들어 놓으셔야 합니다.

아래 이미지의 좌측은 Log창에서의 진행화면이며 우측은 터미널에서 진행화면입니다. 터미널에서 확인 후에 로그 창에서 [enter]를 입력하면서 한단계씩 진행합니다.

사용자 삽입 이미지

아래는 소스파일입니다. 별다른 내용이 없으므로 간단한 주석으로 설명을 대치하였습니다.

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSFileManager *FileManager;
    FileManager = [NSFileManager defaultManager];

    /** 현재 디렉토리에서 test란 디렉토리를 생성 */
    if ([FileManager createDirectoryAtPath:@"test" attributes:nil] == NO ) {
        NSLog(@"Fail to create directory");
        return 0;
    }
    NSLog(@"create directory [press return]");
    getchar();
   
    /** 현재 디렉토리에 test.txt 파일이 있는지 검사 */
    if ([FileManager fileExistsAtPath:@"test.txt"] == NO) {
        NSLog(@"test.txt file not exist");
        return 0;
    }
   
    /** 생성된 test 디렉토리를 test2로 변경 */
    [FileManager movePath: @"test" toPath: @"test2" handler:nil];
    NSLog(@"move directory [press return]");
    getchar();
   
    /** test.txt 파일을 test2 밑에 new_test.txt로 복사 */
    [FileManager copyPath: @"test.txt" toPath: @"./test2/new_test.txt"
        handler:nil];
    NSLog(@"copy file [press return]");
    getchar();
   
    /** 현재 디렉토리를 test2로 이동 후에 new_test.txt를 re_test.txt로 변경 */
    [FileManager changeCurrentDirectoryPath: @"test2"];
    [FileManager movePath: @"new_test.txt" toPath: @"re_test.txt"
        handler:nil];
    NSLog(@"move file [press return]");
    getchar();
   
    /** re_test.txt 파일 삭제 */
    [FileManager removeFileAtPath: @"re_test.txt" handler:nil];
    NSLog(@"delete file [press return]");
    getchar();
   
    /** 현재 디렉토리를 이전 디렉토리로 이동후에 test2 디렉토리 삭제 */
    [FileManager changeCurrentDirectoryPath: @".."];
    [FileManager removeFileAtPath: @"test2" handler:nil];
    NSLog(@"delete directory");
   
    [pool release];

    return 0;
}
AND

Cocoa 파운데이션의 NSFileManager 클래스를 이용하여 특정 패스내의 파일 목록을 검색하고 파일들의 속성을 알아내는 방법입니다. XCode 도움말에서 NSFileManager를 보시면 디렉토리와 파일 관리에 관한 다양한 정보를 확인하실 수 있습니다.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   
    NSFileManager *fileManager;
    NSDirectoryEnumerator *directoryEnum;
    NSString* str;

    fileManager = [NSFileManager defaultManager];

    directoryEnum = [fileManager enumeratorAtPath:
        [fileManager currentDirectoryPath]];
   
    while ((str = [directoryEnum nextObject]) != nil) {
        NSDictionary *dic = [fileManager fileAttributesAtPath: str
                                                 traverseLink: NO];
       
        NSLog(@"%@: %@, %@byte, %@", str,
              [dic objectForKey: NSFileType],
              [dic objectForKey: NSFileSize],
              [dic objectForKey: NSFileOwnerAccountName]);
    }

    [pool release];

    return 0;
}

위의 소스를 빌드하고 실행하면 결과는 아래와 같습니다.

사용자 삽입 이미지

- (NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path
path에 지정된 디렉토리내의 모든 서브 디렉토리와 파일목록을 가져 옵니다.

- (NSDictionary *)fileAttributesAtPath:(NSString *)path traverseLink:(BOOL)flag
path에 지정된 파일 또는 디렉토리의 속성을 가지고 옵니다. flag를 YES로 지정하면 심볼릭 링크된 파일의 원본 파일의 정보를 가져오며, NO일 경우에는 링크된 파일의 정보를 가지고 옵니다.

속성은 NSDictionary의 objectForKey를 이용하여 각각의 속성을 가지고 올 수 있습니다. 각 속성에 대한 Key는 NSFileManager.h에 아래와 같이 정의되어 있습니다.

FOUNDATION_EXPORT NSString * const NSFileType;
FOUNDATION_EXPORT NSString * const NSFileTypeDirectory;
FOUNDATION_EXPORT NSString * const NSFileTypeRegular;
FOUNDATION_EXPORT NSString * const NSFileTypeSymbolicLink;
FOUNDATION_EXPORT NSString * const NSFileTypeSocket;
FOUNDATION_EXPORT NSString * const NSFileTypeCharacterSpecial;
FOUNDATION_EXPORT NSString * const NSFileTypeBlockSpecial;
FOUNDATION_EXPORT NSString * const NSFileTypeUnknown;
FOUNDATION_EXPORT NSString * const NSFileSize;
FOUNDATION_EXPORT NSString * const NSFileModificationDate;
FOUNDATION_EXPORT NSString * const NSFileReferenceCount;
FOUNDATION_EXPORT NSString * const NSFileDeviceIdentifier;
FOUNDATION_EXPORT NSString * const NSFileOwnerAccountName;
FOUNDATION_EXPORT NSString * const NSFileGroupOwnerAccountName;
FOUNDATION_EXPORT NSString * const NSFilePosixPermissions;
FOUNDATION_EXPORT NSString * const NSFileSystemNumber;
FOUNDATION_EXPORT NSString * const NSFileSystemFileNumber;
FOUNDATION_EXPORT NSString * const NSFileExtensionHidden;
FOUNDATION_EXPORT NSString * const NSFileHFSCreatorCode;
FOUNDATION_EXPORT NSString * const NSFileHFSTypeCode;
#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED
FOUNDATION_EXPORT NSString * const NSFileImmutable;
FOUNDATION_EXPORT NSString * const NSFileAppendOnly;
FOUNDATION_EXPORT NSString * const NSFileCreationDate;
FOUNDATION_EXPORT NSString * const NSFileOwnerAccountID;
FOUNDATION_EXPORT NSString * const NSFileGroupOwnerAccountID;
#endif
#if MAC_OS_X_VERSION_10_4 <= MAC_OS_X_VERSION_MAX_ALLOWED
FOUNDATION_EXPORT NSString * const NSFileBusy;
#endif

AND