I’m trying to detect if a given file is a ZIP file by looking at the first four bytes. This is in an iOS app so the file handle stuff is handled by the Cocoa framework, but the actual byte comparison stuff is straight up C, which I don’t really know.
unsigned char aBuffer[4];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *data = [fileHandle readDataOfLength:4];
[data getBytes:aBuffer];
if (aBuffer[0] == 0x50 && aBuffer[1] == 0x4b && aBuffer[2] == 0x03 && aBuffer[3] == 0x04) {
archiveType = ARCHIVE_TYPE_ZIP;
}
It works but strikes me as ungainly. Is there a better way to compare those 4 bytes? (And yes I know it needs more error checking.)
You chould use
memcmp. It’s likestrcmp, but for memory.That said, since you’re using Objective-C you should be looking for a higher-level implementation than C. I suggest building an NSData with the data you expect, then using
[data isEqual: expectedData].You can also use
isEqualToData:instead ifisEqual:. I prefer the short identifier, butisEqualToData:is more efficient and throws when exposed to mismatched types.You’re now very near your intent, rather than the actual mechanics.
@jsd clarified that he was looking for programmer efficiency, rather than runtime efficiency. But for anyone reading this in the future: Forget about runtime efficiency. How often are you checking for a zip header? Instead, worry about how simple the code is and how many ways it can go wrong. And always favour higher-level abstractions when they fit.