开发者

In Cocoa, how do you change the line endings of a file to LF?

开发者 https://www.devze.com 2022-12-10 11:28 出处:网络
Do I ha开发者_开发问答ve to read the files and iterate manually? I\'d like to be able to change between LF and CRLF.I\'m sure there are more memory-efficient ways, but this might do the job for you:

Do I ha开发者_开发问答ve to read the files and iterate manually? I'd like to be able to change between LF and CRLF.


I'm sure there are more memory-efficient ways, but this might do the job for you:

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 is obviously the path to the file; substitute the initWithContentsOfURL:.../writeToURL:... versions if you prefer.


You can use the "tr" command in the terminal.

0

精彩评论

暂无评论...
验证码 换一张
取 消