Heh, I tried this just for the heck of it. I wanted to see if I could read a string from disk w/o knowing anything about its length, only that it has a null-terminator. It could be a single character (and a null), just a null, or a novel.
I exploit the string class''s += operator. I start with an empty string, then I read in a const number of bytes and add it to the string. I check to see if a null is in there, if there is, set the file pointer to be one after that null, otherwise, fillup the buffer again.
Here''s the source for it:
static void ReadString( FILE *f,string& s ) // reads s at file pointer{ static const BufferSize = 1024; // size of buffer/read static char Buffer[BufferSize]; // buffer // parse next BufferSize bytes for the first completed string and return it string Completed; bool ReadEnd = false; while( !ReadEnd ) { // read buffer int BytesRead = fread( Buffer,sizeof( char ),BufferSize - 1,f ); // affix manual terminator (to make sure strlen doesn''t break) if( BytesRead < BufferSize ) Buffer[BytesRead] = 0; else Buffer[BufferSize - 1] = 0; // cache length of read string int Length = strlen( Buffer ); // tack read string to completed Completed += Buffer; // handle completed strings if( (Length < BytesRead) || (Length == 0) ) { // seek back to first null terminator fseek( f,Length - BytesRead + 1,SEEK_CUR ); ReadEnd = true; } } s = Completed;}//---------------------------------------------------------------------------
|
I wouldn''t say it''s entirely efficient, but it works and you don''t need an encoded length, so it''ll read any string.
Hope it helps in some way.
Thank you for your bandwidth.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~Succinct Demos Online~
I am a software engineer who writes poetic code!