我一直在試圖將字符串附加到本地資源文件,但我無法找到解決方案。我試圖爲我的應用程序中的所有函數調用創建一個日誌文件,所以如果它崩潰,我可以看到它停止的功能。如何在iOS的本地資源txt文件中附加字符串sdk
我已創建一個log.rtf文件,但無法寫入此文件。有人可以幫助我追加一個字符串到這個文件,而不必覆蓋整個事情?
我一直在試圖將字符串附加到本地資源文件,但我無法找到解決方案。我試圖爲我的應用程序中的所有函數調用創建一個日誌文件,所以如果它崩潰,我可以看到它停止的功能。如何在iOS的本地資源txt文件中附加字符串sdk
我已創建一個log.rtf文件,但無法寫入此文件。有人可以幫助我追加一個字符串到這個文件,而不必覆蓋整個事情?
我對以上問題使用以下代碼。
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];
- (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];
}
這樣你就可以做到這一點..
+ (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);
}
}
感謝Sachin,但是這會增加文件的開始,而不是文件的結尾。 –
@添, '將writeToFile:原子:' 從XCode的4.1 –
不贊成我更新了我的代碼=)! – elslooo
如果文件的大小超過10k,該怎麼辦?然後可變字符串不能容納這麼多的數據,那麼它會導致應用程序崩潰。請試試這個,讓我知道。採取一個txt文檔。使用10k大小並嘗試使用此代碼追加一行。 –