How to append string in local resource txt file for iOS sdk

旧城冷巷雨未停 提交于 2019-12-18 01:14:15

问题


I have been trying to append strings to a local resource file but I am having trouble finding a solution. I am trying to create a log file for all the function call in my application so if it crashes I can see which function it stopped on.

I have created a log.rtf file, but am not able to write in this file. Can someone please help me append a string to this file without having to overwrite the entire thing?


回答1:


I have use following code for the above problem.

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];



回答2:


This way you can do this..

+ (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);
        }

}



回答3:


- (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];
}


来源:https://stackoverflow.com/questions/7041237/how-to-append-string-in-local-resource-txt-file-for-ios-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!