2011-02-28 3 views
1

iOS의 파일에서 마지막 줄을 제거하려면 어떻게해야합니까?파일의 마지막 줄 삭제하기 iPhone iOS

다음은 파일 끝으로 이동하지만 그 마지막 줄을 제거하는 방법을 모르는 코드입니다.

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

//make a file name to write the data to using the documents directory: 
NSString *file = [NSString stringWithFormat:@"%@/%@.daa", documentsDirectory, MFILE_NAME]; 

NSFileHandle *aFileHandle = [NSFileHandle fileHandleForWritingAtPath:file]; 
//setting aFileHandle to write at the end of the file 
[aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; 

도움 주셔서 감사합니다. 이 글을 읽고 몇 가지 문서는 내가 함께 결국 무엇 후

답변

1

좋아, : 당신은 더 좋은 방법을 알고 있다면

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *file = [NSString stringWithFormat:@"%@/%@.txt", documentsDirectory, @"file_name"]; 

    NSData *orgData = [NSData dataWithContentsOfFile:file]; 

    //Because there is only one char on my last line I make a range from 0 to length of data - 1 byte. 
    NSRange range = {0, [orgData length]-1}; 

    NSData* shortData = [[NSData dataWithContentsOfFile:file] subdataWithRange:range]; 

    [shortData writeToFile:file atomically:YES]; 

알려 주시기 바랍니다.

0

파일에 따라 괜찮을 수도 있습니다.

한 문자를 제거해도 후행 캐리지 리턴과 같은 것은 처리되지 않으므로 실제로는 실제로 작동하지 않을 수 있습니다. 더 나은 (더 일반적인) 솔루션은 파일을로드하고 마지막 줄의 시작 부분 (즉, 마지막 캐리지 리턴과 마지막 줄 사이의 모든 항목)을 찾을 때까지 마지막 문자에서 뒤로 이동 한 다음 마지막 줄없이 파일을 다시 작성하십시오.

1

확신이 당신의 해결책이 될 수있다 :

NSFileHandle *file; 
file = [NSFileHandle fileHandleForUpdatingAtPath:[self filePath]]; 

if (file == nil) 
    NSLog(@"Failed to open file"); 

//get the last character count 
long long lastChar = [file seekToEndOfFile]; 
lastChar--; 
lastChar--; 

//from where do you want to remove 
NSLog (@"Offset = %llu", lastChar); 
//Move to position 
[file seekToFileOffset: lastChar]; 

//write an empty string 
[file writeData:[@" " dataUsingEncoding:NSUTF8StringEncoding]]; 

[file closeFile]; 
관련 문제