Reading and writing binary I/O in C.


Source listing
//------------------------------------------------------
// File: Code603_FileIO.cpp
// Purpose: Demonstration of binary I/O in ANSI Standard C
// Programming Language: C
// Author: Dr. Rick Coleman
//---------------------------------------------------------------
#include <stdio.h>

struct simple
{
    int num;
    char ch;
};

int main(void)
{
    FILE *fptr;        // pointer to FILE
    simple sim;
    char ch;

    fptr=fopen("structfile.bin", "wb");
    //------------------------------------------------------
    //  Writing structures to a file
    //  I/O function:  long fwrite(void *buffer, long size,
    //                           long numObjects, FILE *fp)
    //------------------------------------------------------
    do
    {
        printf("Type an int and a char.\n");
        scanf("%d %c", &sim.num, &sim.ch);
        fwrite(&sim, sizeof(struct simple), 1, fptr);
        printf("Add another structure to disk(y/n)?  ");
        fflush(stdin); // Flush the keyboard buffer
        ch = getc(stdin);
    }
    while(ch =='y');

    fclose(fptr);
    //------------------------------------------------------
    //  Reading structures from a file
    //  I/O function:  long fread(void *buffer, long size,
    //                           long numObjects, FILE *fp)
    //------------------------------------------------------
    if( (fptr = fopen("structfile.bin", "rb")) == NULL)
    {
        printf("Can't open structfile.bin.\n");
        return 0;
    }
    while (fread(&sim, sizeof(struct simple), 1, fptr)==1)
        printf("%d %c\n", sim.num, sim.ch);
    fclose(fptr);
    return 0;
}