I am trying to write all log message in to text file. How can i write all logs in to text file if it is empty and if already have some data then append new log messages at the end of file.
我正在尝试将所有日志消息写入文本文件。如果它是空的并且如果已经有一些数据然后在文件末尾添加新的日志消息,我如何将所有日志写入文本文件。
How may i achieve this.
我怎么能实现这一点。
NSString* loggerFileName = nil;
loggerFileName = [thisBundle pathForResource:@"Logger" ofType:@"txt"];
NSMutableString *logger = [[NSMutableString alloc] initWithString:@"Loggers maintain here"];
[logger appendFormat:@"\nCurrent user id is $: %@",UserID];
NSLog(@"logger contains...*** : %@",logger);
[logger writeToFile:loggerFileName atomically:YES encoding:NSUnicodeStringEncoding error:nil];
By using above code, I can write to file but i am not able to append more logs on same text file.
通过使用上面的代码,我可以写入文件,但我无法在同一文本文件上追加更多日志。
Help me how may i do this. Thanks in advance.
帮帮我怎么做呢提前致谢。
Thanks, Vikas s.
谢谢,维卡斯。
2 个解决方案
#1
1
I believe this is what you are looking for write data line by line on iphone
我相信这就是你在iphone上逐行寻找写入数据的原因
#2
6
Here is an NSString category method that will append the receiver to the specified path with the specified encoding (normally NSUTF8StringEncoding).
这是一个NSString类别方法,它将接收器附加到具有指定编码的指定路径(通常是NSUTF8StringEncoding)。
- (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc;
{
BOOL result = YES;
NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:path];
if ( !fh ) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
fh = [NSFileHandle fileHandleForWritingAtPath:path];
}
if ( !fh ) return NO;
@try {
[fh seekToEndOfFile];
[fh writeData:[self dataUsingEncoding:enc]];
}
@catch (NSException * e) {
result = NO;
}
[fh closeFile];
return result;
}
#1
1
I believe this is what you are looking for write data line by line on iphone
我相信这就是你在iphone上逐行寻找写入数据的原因
#2
6
Here is an NSString category method that will append the receiver to the specified path with the specified encoding (normally NSUTF8StringEncoding).
这是一个NSString类别方法,它将接收器附加到具有指定编码的指定路径(通常是NSUTF8StringEncoding)。
- (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc;
{
BOOL result = YES;
NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:path];
if ( !fh ) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
fh = [NSFileHandle fileHandleForWritingAtPath:path];
}
if ( !fh ) return NO;
@try {
[fh seekToEndOfFile];
[fh writeData:[self dataUsingEncoding:enc]];
}
@catch (NSException * e) {
result = NO;
}
[fh closeFile];
return result;
}