I've some text files with accented characters, but I do not know the encoding, and I want the text to be displayed as-is in a NSTextField.
I can use [NSString stringWithContentsOfFile:] but this method is deprecated. All the other methods require the user to supply the text encoding. I don't want to use any methods that would try to guess at the encoding, because: 1. they won't work all the times, 2. I really just want to display the contents of the file the way it is in NSTextField.
So what should I do?
I really just want to display the contents of the file the way it is in NSTextField.
You are asking the impossible, "the way it is" depends on the encoding. The file contains a sequence of bytes, which are just strings of eight 0's & 1's. You have to interpret those strings of bits. You can take them four at a time and interpret them as 32 bit integers, or 32 bit floats, or UTF32 – and you'll get a different result each time. Or you can take them one at a time and interpret them as ASCII, UTF, EBCDIC, etc, etc, etc – and you'll get different results.
The closest you get to "the way it is" is to dump the bytes in binary, octal or hex – i.e. what the od
command line command will do for you. You can try to figure it out, e.g. as the file
command does, or you need to know. (See also this question.)
I ended up using:
[NSString stringWithContentsOfFile:filePath encoding:[NSString defaultCStringEncoding] error:nil]
This gives me the same result as [NSString stringWithContentsOfFile:]