파일 입출력 테스트 함수

먼저 파일 시스템에 파일을 쓰고 읽으려면 당연하겠지만, 파일을 하나 생성해 놔야 합니다. (NSFileManager::createFilePath를 활용)
그렇지만 만일 실행파일 내의 리소스 안의 파일에 대해 (리소스 번들) 읽고 쓰려면 파일 생성을 해놓는것이 아니라, xib가 있는 Resource 노드에 파일 하나를 생성해 놓으면 되지요. (이에 대해선 아래에 다시 그림으로 설명하겠습니다 ^^)

아래 예제는 각 애플리케이션 마다 존재하는 다큐먼트 디렉터리에 파일을 하나 생성하고, 그 파일에 대해서 쓰고 읽는 예제입니다.
재미있는 점은 파일  I/O 는 NSData를 사용해야 한다는 점이다. 따라서 NSString을 NSData로 서로 변환하는 것을 볼 수 있습니다.

마지막으로 생성된 파일의 위치는 iPhone Simulator에서 실행했을 때와 실제 Device에서 실행했을 때 각각 다릅니다. 아래 주석으로 그 패스를 설명해놓았으니, 실행해 보신 후 해당 패스를 가보시면 파일이 만들어져 있는것을 확인해 볼 수 있습니다.

- (void) TestFile_ReadWrite {

/////////////////////////////////////////////////////////////////////////////

// 파일 시스템의 디렉터리 파일 준비

/*

Document Directory Full Path

--------------------------

iPhone Simulator : /Users/kyungmincho/Library/Application Support/iPhone Simulator/User/Applications/7AE9E3F3-3347-4B73-BA73-DCF6A9AFA57B/Documents/

Actual Device : /var/mobile/Applications/7AE9E3F3-3347-4B73-BA73-DCF6A9AFA57B/Documents/

*/

   

// Get documents directory

NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(

  NSDocumentDirectory,

  NSUserDomainMask,

  YES);

NSString* docDir = [arrayPaths objectAtIndex:0];


NSString *filePath = [docDir stringByAppendingString:@"/test.txt"];


// 먼저 파일을 생성한다.

[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];


/////////////////////////////////////////////////////////////////////////////

// 리소스 안에 하려면 Workspace Resources에서 AddFile/Mac OSX/Empty file 추가함.

// 실행 파일 리소스에 있는 파일을 열어서 수정하고자 하면 아래 패스 사용

    //NSString *filePath = [NSString stringWithFormat: @"%@/test.txt", [[NSBundle mainBundle] resourcePath]];


NSLog(filePath);

// 파일에 기록할 내용을 마련한다.

NSString* sText = [NSString stringWithFormat: @"Hello world modified"];

NSUInteger nLen = [sText length];

// NSFileHandle 사용하는 파일 저장용 데이터 타입은 NSData이다

NSData* pData = [sText dataUsingEncoding:NSUTF8StringEncoding];

////////////////////////////////////////////////////////////////////////

// 파일 쓰기 테스트

// 파일을 연다.

    NSFileHandle *hFile = [NSFileHandle fileHandleForWritingAtPath:filePath];

if ( hFile == nil )

{

NSLog(@"no file to write");

return ;

}

// 파일을 쓰고 파일 포인터를 전진하고 파일을 닫는다.

[hFile writeData:pData];

    [hFile truncateFileAtOffset:nLen];

    [hFile closeFile];

////////////////////////////////////////////////////////////////////////

// 파일 쓰기 테스트

// 파일을 연다.

    NSFileHandle *hFile2 = [NSFileHandle fileHandleForReadingAtPath:filePath];

if ( hFile2 == nil )

{

NSLog(@"no file to read");

return ;

}

// 파일을 읽고 파일을 닫는다.

    NSData* pData2 = [hFile2 readDataOfLength:nLen];

    [hFile2 closeFile];

// NSData 화면에 출력할 있는 NSString 타입을 변환한다.

NSString* sReadString = [[NSString alloc] initWithData:pData2 encoding:NSUTF8StringEncoding];

// 디버그 콘솔에 내용을 출력한다.

NSLog(sReadString);

}


만일 리소스 내 파일에 대해서 하고 싶다며
만일 리소스 번들 파일로 만드려면 아래처럼 리소스 안에 파일을 하나 생성해 두면 됩니다.

그리고는 위에 주석을 달아놨던 코드 부분 아래 부분을 주석을 풀어주고 살짝 수정해주면 되겠네요.

/////////////////////////////////////////////////////////////////////////////

// 리소스 안에 하려면 Workspace Resources에서 AddFile/Mac OSX/Empty file 추가함.

// 실행 파일  리소스에 있는 파일을 열어서 수정하고자 하면 아래 패스 사용

    //NSString *filePath = [NSString stringWithFormat: @"%@/test.txt", [[NSBundle mainBundle] resourcePath]];


+ Recent posts