Objective c 在Cocoa中,如何将文件的行尾更改为LF?

Objective c 在Cocoa中,如何将文件的行尾更改为LF?,objective-c,cocoa,file-io,Objective C,Cocoa,File Io,我必须读取文件并手动迭代吗?我希望能够在LF和CRLF之间切换。您可以在终端中使用“tr”命令。我确信有更节省内存的方法,但这可能会为您完成以下工作: NSStringEncoding usedEncoding; NSMutableString *fileContents = [[NSMutableString alloc] initWithContentsOfFile:pathToFile usedEncoding:&usedEncoding error:nil]; // Norma

我必须读取文件并手动迭代吗?我希望能够在LF和CRLF之间切换。

您可以在终端中使用“tr”命令。

我确信有更节省内存的方法,但这可能会为您完成以下工作:

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
显然是文件的路径;如果愿意,可以将
初始化替换为contentsofURL:…
/
writeToURL:…
版本。

您能解释一下,您想做什么吗?您是要更改磁盘上的文件,还是只读取文件时要更改行尾?在这种情况下,我更喜欢更改磁盘上的文件。在Cocoa中,如果不使用NSTask运行命令,则无法执行此操作?我刚刚意识到,如果读取已使用CRLF行尾的文件,这将导致问题;希望您已经提前知道/正在检测到这一点。>_