iphone - 删除文件 iPhone iOS 中的最后一行

标签 iphone ios file-io

如何在 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/

相关文章:

ios - 精确安排iOS 7中的声音

iOS UIPageControl 改变位置

c# - 根据从 C# 编写的方式,两个相同的文件具有不同的文件大小

c - 在 UNIX 系统 (Ubuntu 10.10) 上用 C 语言读取二进制文件

java - 在文件中有效地存储 float 和 short 值的数组

ios - 将应用程序上传到应用程序商店,支持 iPad,稍后支持 iPhone

iphone - 在 iPhone 中是否有任何标准方法来实现 "blue badge"?

iphone - 可以部分释放一 block 内存吗?

javascript - 使用一个 http 请求下载文件,无需压缩

iphone - Objective-C UImage imageWithData问题