Cocoa OSX中的writeToFile,是否附加到该文件?
我需要不时地将一些数据写入一个文件,并附加到该文件中 现在我有:Cocoa OSX中的writeToFile,是否附加到该文件?,cocoa,macos,file,Cocoa,Macos,File,我需要不时地将一些数据写入一个文件,并附加到该文件中 现在我有: BOOL ok = [[NSString stringWithFormat:@"%f",raw] writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:&error]; 如何将raw的新内容附加到文件末尾?一种方法是使用fileHandleForWritingAtPath:方法获取NSFileHandle,将NSString转换为NS
BOOL ok = [[NSString stringWithFormat:@"%f",raw] writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:&error];
如何将
raw
的新内容附加到文件末尾?一种方法是使用fileHandleForWritingAtPath:方法获取NSFileHandle,将NSString转换为NSData,然后在将文件指针移到文件末尾后在NSFileHandle上调用writeData: 这里有一个NSString category方法,它将使用指定的编码(通常为NSUTF8StringEncoding)将接收器附加到指定路径
编辑Peter N Lewis的回答:
- (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:[strcontent dataUsingEncoding:enc]];
}
@catch (NSException * e) {
result = NO;
}
[fh closeFile];
return result;
}
你想打哪儿就打哪儿
[self appendToFile:fileName encoding:NSUTF8StringEncoding];
strcontent
当您将此方法放入NSString类别时,可能是self
。这是我的Swift版本,不完全相同,但它可以工作。我决定不扩展字符串,这样就可以将其用作编写的替代项(exportFileNameURL:URL,str:String)
对-写。。。方法用正在写入的内容覆盖文件。没有“appendTo…”等价物。尽管如此,我不认为在NSString上编写category方法会非常困难,该方法实现了appendToFile…+1以提供执行该任务的代码。(国际海事组织,这应该是公认的答案。)
[self appendToFile:fileName encoding:NSUTF8StringEncoding];
fileprivate static func appendToFile(_ exportFileName: String, str: String) -> Bool {
let result : Bool = true;
if let fh : FileHandle = FileHandle.init(forWritingAtPath: exportFileName) {
fh.seekToEndOfFile()
fh.write(str.data(using: String.Encoding.utf8)!)
fh.closeFile()
}
else {
FileManager.default.createFile(atPath: exportFileName, contents: nil, attributes: nil)
if let fh = FileHandle.init(forWritingAtPath: exportFileName) {
fh.seekToEndOfFile()
fh.write(str.data(using: String.Encoding.utf8)!)
fh.closeFile()
}
else {
return false;
}
}
return result
}