TOC | Prev

Basic writing

File output is basically memcpy to the filesystem.

files.c

#include <stdio.h>
#include <memory.h>
#include <errno.h>

typedef struct employee_t {
    char name[40];
    int onsite;
    struct {
        int floor;
        char quadrant;
        int cube;
    } location;
} employee;

const char * const filename = "/tmp/employees";


int main( int argc, const char **argv ) {
    employee me;
    size_t bytes;
    FILE *fp;

    memset( &me, 0, sizeof( me ) );
    strcpy( me.name, "Andy Lester" );
    me.location.floor    = 4;
    me.location.quadrant = 'B';
    me.location.cube     = 14;
    me.onsite            = 1;

    fp = fopen( filename, "w" );
    if ( !fp ) {
        printf( "Couldn't create %s: %d\n", filename, errno );
    }
    bytes = fwrite( (const void *)&me, sizeof(me), 1, fp );
    if ( bytes < 1 ) {
        printf( "Only wrote out %lu bytes, not %lu bytes\n", bytes, sizeof(me) );
    }
    fclose( fp );

    return 0;
}

$ files && xxd /tmp/employees

0000000: 416e 6479 204c 6573 7465 7200 0000 0000  Andy Lester.....
0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000020: 0000 0000 0000 0000 0100 0000 0400 0000  ................
0000030: 4200 0000 0e00 0000                      B.......
TOC | Prev