我是否需要阅读文件并手动进行迭代?我希望能够在LF和CRLF之间进行切换。
最佳答案
我敢肯定还有更多内存有效的方法,但这可能为您完成工作:
NSStringEncoding usedEncoding;
NSMutableString *fileContents = [[NSMutableString alloc] initWithContentsOfFile:pathToFile usedEncoding:&usedEncoding error:nil];
// Normally you'd pass in an error and do the checking thing.
[fileContents replaceOccurrencesOfString:@"\n" withString:@"\r\n" options:NSLiteralSearch range:NSMakeRange(0, [fileContents length])];
// The other direction: [fileContents replaceOccurrencesOfString:@"\r\n" withString:@"\n" options:NSLiteralSearch range:NSMakeRange(0, [fileContents length])];
// Assumes you want to overwrite the file; again, normally you'd check for errors and such.
[fileContents writeToFile:filePath atomically:YES encoding:usedEncoding error:nil];
[fileContents release];
pathToFile
显然是文件的路径;如果愿意,可以替换initWithContentsOfURL:...
/ writeToURL:...
版本。