I have a program that scans a big file looking for some text.
Here the two lines that load the file mapping it in memory to avoid loading it entirely if it is a big file.
NSData *buf = [NSData dataWithContentsOfFile:sourceFile options:NSDataReadingMappedIfSafe error:&err];
NSMutableString *string = [[NSMutableString alloc] initWithBytesNoCopy:(void *)buf.bytes length:buf.length encoding:NSASCIIStringEncoding freeWhenDone:NO];
How can i open it without providing the NSASCIIStringEncoding, given that i will not know what encoding file does have?
Well, the point is, IMO, that you cannot create a string from some bytes without specifying which encoding should be used to interpret those bytes.
You don’t know, and that is fine, that the OS would not know either, and that will simply not work. An encoding will be used, so you are better off if you specify one.
On the other hand, if you are really troubled at this and foresee the need to support various encodings, keep in mind that if you specify a wrong encoding, then the string creation will fail (you get nil). If that happens you could try with a different encoding, and so on until you find an encoding that fits. (Provided your data is representable as a string at all).