Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
"Mastering C Pointers"....
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
Reply to thread
Message
[QUOTE="Chris Torek, post: 1685928"] (Yes. Left in just to establish context.) In C, the term "string" really refers to a data *format*, rather than anything in the type, value, object, etc., sense. Suppose I were to tell you that I have a set of (binary) files in which each "record" is a variable-length region prefixed by two eight-bit bytes giving the length of the record in big- or little-endian format (i.e., I tell you which byte to multiply by 256 before adding the other, to get the length). You then find the record length by doing: c1 = getc(fp); c2 = getc(fp); if (c1 == EOF || c2 == EOF) ... handle trouble and/or EOF ... len = c1 * 256 + c2; /* if big-endian */ len = c2 * 256 + c1; /* if little-endian */ Having done this, you can now read the record -- which is "len" bytes long -- or skip over it using fseek(), for instance. What I have done is describe a data format for the file. As long as you have a valid starting point from which to read the file's records, you can read through all the records in the file, and detect a "short read" if the file ends too soon (in the middle of a record, or with c2==EOF but c1!=EOF in the above code). A C string is just a data format in memory -- simpler than the record format in this file, because there is no leading count to interpret, but a data format nonetheless. You could write a sequence of strings to a binary file and then read them back by reading bytes until you find each '\0' -- each such set of bytes is a "string" in the file. Since a string is a data format, you must store it in some other data object. A sequence of bytes ending with a '\0' will fit in *any* C object of sufficient size (due to C's requirement that all objects break down into a sequence of "unsigned char" bytes), but the most suitable is a sufficiently large array of char (or unsigned char, in some special circumstances). Among other things, this means that you can -- nonportably, but perhaps tested at compile time -- store 7-or-fewer-character C strings in "double"s, as long as sizeof(double) >= 8 (as is fairly typical). But you must then use considerable care never to access those "double"s as lvalues of type "double", since the bit patterns created by strings might be reserved when treated as ordinary "double", and cause a runtime trap. (Modern IEEE-fp machines in particular will trap "signalling NaNs" if the NaN trap is enabled.) This is thus the kind of code one should only use in an "obfuscated C" contest. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
"Mastering C Pointers"....
Top