Using the HTML5 File API I can get the Binary String representation of a file using FileReader.readAsBinaryString(). For an image this might return: “”ÿØÿàJFIFHHÿáExifMM*bj(1r2i¤ÐHHAdobe Photoshop CS Windows2006:07:12 15:24:47 ÿÿ…”. Using Objective-C, I’m trying to get the same representation of a file.
NSData *data = [NSData dataWithContentsOfFile:path];
unsigned char *aBuffer = malloc([data length]);
[data getBytes: aBuffer length:[data length]];
return [[NSString alloc] initWithBytes:aBuffer length:[data length] encoding:NSASCIIStringEncoding];
The above has two issues (at least), there is a memory leak and the output is only ‘ÿØÿà’. How do I get the full string and avoid a memory leak?
Edit when I do this:
NSData *data = [NSData dataWithContentsOfFile:path];
return [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding];
I get the exact same output.
WebKit does the following (in C++):
m_stringResult = String(static_cast<const char*>(m_rawData->data()), m_bytesLoaded);
That is within FileReaderLoader.cpp, line 252. It is within WebCore, which is within WebKit.
For the memory leak: have you heard of -autorelease?
For the core problem:
NSString assumes to get a C string as its “bytes” parameter. So it will only get the file contents up to a 0x00 byte, which it interprets as a ‘terminating NUL’ character.
By the way, the correct method to do it is not forcing a poor NSString instance to initialize itself with invalid (non-ASCII, non-string!) garbage. You’d better use NSData’s -bytes method to get a byte array. You can even access its individual bytes using something like this: