Fundamental C - Files
Written by Harry Fairhead   
Monday, 20 January 2020
Article Index
Fundamental C - Files
Text Mode
Structs As Records

Structs as Records

When you are working with binary files you have to establish and stick to a very regular format. Usually the simplest way to do this is to create a struct that has the data you want to save and load and make use of this to structure your file.

For example, a record might consist of a name and age. A suitable struct would be:

struct person {
    char name[25];
    int age;

To write a single record out to file:

struct person me;
me.age = 18;
FILE *f = fopen("myFile.bin", "wb");
fwrite(&me, sizeof (struct person), 1, f);

To read the data back:

struct person me2;
f = fopen("myFile.bin", "rb");
fread(&me2, sizeof (struct person), 1, f);
printf("%s  %d",, me2.age);

Notice that the struct is treated as a single entity and all of the bytes it uses are written to the file and then read back in.

You can, of course, write multiple records and read multiple records back in one at a time if you want. The key idea is that rather than trying to structure the file by writing variables of different types it is much easier to create a suitable struct and read and write it as a single unit.

In chapter but not included in this extract:

  • Buffering
  • Character I/O
  • Positioning Functions
  • End Of File Errors
  • Random Access
  • File Operations
  • Sharing Files – Locking


  • If you think of a file as just a sequence or stream of bytes that can be read or written then you have an idea that fits a great many sources and sinks of data.

  • This idea is so powerful that under Linux/Unix you can view almost all data as an example of a file.

  • C has a standard way of working with files – streams – and it provides a range of functions for working with file pointers such as fopen and fclose.

  • In text mode a C file can be accessed using fprintf and fscanf which are file versions of printf and scanf.

  • In binary mode you can use fread and fwrite to work with binary data as sets of bytes.

  • The natural way to organize binary files is to use structs as if they were records.

  • C files are buffered and this can cause unexpected behavior. Use fflush to make sure that buffers are written out.

  • You can also use lower level character functions fgetc and fputc.

  • Files are read from the current position which can be changed using rewind or fseek. You can find the current position using ftell.

  • Detecting the end of a file is sometimes difficult as EOF is returned if there is an error as well as when the end of file has been reached.#

  • Using file positioning and structs it is very easy to implement a simple database.

  • There are a range of file manipulation commands that allow you to do things like rename files.

  • Linux/Unix file locking is troublesome and it is better to implement your own locking from first principles.



Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation
  6. Operators and Expression
      Extract: Expressions
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays
      Extract  Ennumerations
  9. Strings
      Extract  Simple Strings
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
    Extract Random Access Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C






Harry Fairhead is the author of Raspberry Pi IoT in C ,  Micro:bit IoT in C and Fundamental C: Getting Closer to the Machine. His latest book is  Applying C For The IoT With Linux.

Related Articles

Remote C/C++ Development With NetBeans

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.


We Built A Software Engineer

One of the most worrying things about being a programmer today is the threat from AI. It has gone so far that NVIDA CEO Jensen Huang proclaims that you really shouldn't start training as a programmer  [ ... ]

Conference Times Ahead

Following a well-established pattern both Google's and Microsoft's Developer Conferences will take place in May while Apple follows on in June. Here are the dates plus what to expect.

More News

raspberry pi books



or email your comment to:

Last Updated ( Monday, 20 January 2020 )