Replace your method:
[str writeToFile:pdfPath atomically:YES];
With:
[str writeToFile:pdfPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
Question
In my application,
I have create .txt file programatically. file create successfully. but \n is not working in this file.
I have use following code for this.
NSString *str=[NSString stringWithFormat: @"line 1 \nline 2 \nline 3"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",@"REFINESEARCH"]];
[str writeToFile:pdfPath atomically:YES];
When I open REFINESEARCH.txt file in mac it will working fine. But when I open this file in windows OS. it's looking like this..
\n is not working here. how to solve this?
Solution
Replace your method:
[str writeToFile:pdfPath atomically:YES];
With:
[str writeToFile:pdfPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
OTHER TIPS
Windows (or more specifically, Notepad) uses carriage return/line feed to display new lines. Use \r\n
instead and you should be fine.
Modiifed your code as only (\r) will work so just replace \n to \r and try:-
NSString *str=[NSString stringWithFormat:@"line 1 \rline 2 \rline 3"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",@"REFINESEARCH"]];
[str writeToFile:pdfPath atomically:YES];