如何在 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]];
感谢您的帮助。
最佳答案
好的,在阅读了一些文档之后,这就是我最终得到的:
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];
如果你知道更好的方法请告诉我。
关于iphone - 删除文件 iPhone iOS 中的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5142415/