1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Random Access File Handling

By , About.com Guide

9 of 9

More About Example 2

Having obtained the size and position of the data, it just remains to fetch it.
fsetpos( ftdata, &index.pos ) ;
fread( text,index.size, 1, ftdata) ;
text[ index.size ]='\0';
Here I've used fsetpos() because of the type of index.pos which is fpos_t. An alternative way is to use ftell instead of fgetpos and fsek instead of fgetpos. The pair fseek and ftell work with int whereas fgetpos and fsetpos use fpos_t.

After reading the record into memory, a null character \0 is appended to turn it into a proper c-string. Don't forget it or you'll get a crash. As before fclose is called on both files. Althogh you won't lose any data if you forget fclose (unlike with writes) you will have a memory leak.

Performance Note

Most operating systems employ buffering with files but in my experience the file buffers are not that big. If you were using this example on large files, it might be faster to store the index structs in memory and write the data file in one loop, then write all the index structs into a file.

Buffering is more relevant with text files as we'll see in the next lesson.

This completes this C programming tutorial on random access files. The next one will be on text files.

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. More About Example 2

©2009 About.com, a part of The New York Times Company.

All rights reserved.