HERE'S HOW: distinguish old archives from keyed archives
HERE'S HOW: distinguish old archives from keyed archives
- Subject: HERE'S HOW: distinguish old archives from keyed archives
- From: Chris Kane <email@hidden>
- Date: Sun, 31 Aug 2003 12:21:02 -0700
Since a lot of questions have popped up here on how to distinguish an
NSArchiver archive from an NSKeyedArchiver archive, I thought I'd make
some remarks.
First of all, IMHO, you should be using a different file extension for
a new document format which is keyed-archiving-based rather than
old-archiving-based. It's a different file format after all. But most
of you won't listen to that advice.
What you should do to distinguish is look at the first few bytes of the
data (the "magic number").
If the data is at least 13 bytes long, and the 2nd - 13th bytes are
"\00btypedstream" or "\00bstreamtyped" then you have an old archive.
if (13 <= length &&
(0 == memcmp((char *)bytes + 1, "\00btypedstream", 12)
|| 0 == memcmp((char *)bytes + 1, "\00bstreamtyped", 12))) -> OLD
ARCHIVE
If the data is at least 6 bytes long, and the first six bytes are
"bplist", then you have a binary plist, and if you're expecting a keyed
archive, you can assume that it is until you get further in.
NSKeyedUnarchiver itself will throw an exception if it doesn't
recognize the file, modulo bugs in lower layers of the system.
if (6 <= length &&
0 == memcmp((char *)bytes, "bplist", 6)) -> BINARY PLIST, possibly
keyed archive
Detecting an XML-format keyed archive is more difficult, since the XML
declaration <?xml ...> is optional, strictly speaking, and whitespace
and comments can get in the way later. My recollection is that if the
XML declaration is present it must be the first thing without preceding
whitespace, but I could be wrong there. A heuristic would be to check
the first 5 characters. It's pretty safe to assume that
NSKeyedArchiver will always put an XML declaration at the beginning.
if (5 <= length &&
0 == memcmp((char *)bytes, "<?xml", 5)) -> probable XML FILE,
possibly keyed archive
Otherwise, the file is either something else, or has been hand-edited,
and/or corrupted. And of course these checks don't protect you from
files which have been corrupted or truncated or had one sector from
another file inserted into the middle of it by the file system or
whatever.
Chris Kane
Cocoa Frameworks, Apple
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.