2011-08-12 37 views
10

我一直在试图将字符串附加到本地资源文件,但我无法找到解决方案。我试图为我的应用程序中的所有函数调用创建一个日志文件,所以如果它崩溃,我可以看到它停止的功能。如何在iOS的本地资源txt文件中附加字符串sdk

我已创建一个log.rtf文件,但无法写入此文件。有人可以帮助我追加一个字符串到这个文件,而不必覆盖整个事情?

回答

31

我对以上问题使用以下代码。

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDir = [documentPaths objectAtIndex:0]; 
NSString *logPath = [[NSString alloc] initWithFormat:@"%@",[documentsDir stringByAppendingPathComponent:@"log.rtf"]]; 
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:logPath]; 
[fileHandler seekToEndOfFile]; 
[fileHandler writeData:[text dataUsingEncoding:NSUTF8StringEncoding]]; 
[fileHandler closeFile]; 
0
- (void)log:(NSString *)message { 
    NSMutableString *string = [[NSMutableString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]]; 
    if (!string) string = [[NSMutableString alloc] init]; 
    [string appendFormat:@"%@\r\n", message]; 
    [string writeToFile:[NSString stringWithFormat:@"%@/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
} 
+0

@添, '将writeToFile:原子:' 从XCode的4.1 –

+0

不赞成我更新了我的代码=)! – elslooo

+1

如果文件的大小超过10k,该怎么办?然后可变字符串不能容纳这么多的数据,那么它会导致应用程序崩溃。请试试这个,让我知道。采取一个txt文档。使用10k大小并尝试使用此代码追加一行。 –

0

这样你就可以做到这一点..

+ (void)WriteLogWithString:(NSString *)log 
{ 

     if(log != nil){ 

      NSString *locationFilePath = [self getLogFilePath];//access the path of file 

      FILE *fp = fopen([locationFilePath UTF8String], "a"); 

      fprintf(fp,"%s\n", [log UTF8String]); 

      fclose(fp); 
     } 

} 
+0

感谢Sachin,但是这会增加文件的开始,而不是文件的结尾。 –

相关问题