Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created September 9, 2022 23:19
Show Gist options
  • Select an option

  • Save EteimZ/0ee01d330f1b1c36119858ff830160f0 to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/0ee01d330f1b1c36119858ff830160f0 to your computer and use it in GitHub Desktop.
Example of working with binary files in C.
struct clientData {
int acctNum; // account number
char lastName[ 15 ]; // account last name
char firstName[ 10 ]; // account first name
double balance; // account balance
};
/*
Create binary file with C to store customer data
Source: C How to Program by The Dietels
*/
#include <stdio.h>
#include "client.h"
int main( void ){
int i;
struct clientData blankClient = { 0, "", "", 0.0 };
FILE *fPtr = fopen("client", "wb");
if ( fPtr == NULL){
printf("File could not be opened.\n");
}
else {
// output 100 blank records to file
for ( i = 0; i < 100; i++)
{
fwrite(&blankClient, sizeof( struct clientData ), 1, fPtr);
}
fclose(fPtr);
}
return 0;
}
/*
Read from binary file to get customer data
Source: C How to Program by The Dietels
*/
#include <stdio.h>
#include "client.h"
int main( void ){
FILE *fPtr = fopen("client", "rb");
struct clientData client = { 0, "", "", 0.0};
if ( fPtr == NULL){
printf("File could not be opened.\n");
} else
{
printf("%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" );
while ( !feof(fPtr) )
{
fread( &client, sizeof( struct clientData ), 1, fPtr );
if ( client.acctNum != 0 ){
printf( "%-6d%-16s%-11s%10.2f\n",
client.acctNum, client.lastName,
client.firstName, client.balance );
}
}
fclose(fPtr);
}
return 0;
}
/*
Write to binary file to create customer data
Source: C How to Program by The Dietels
*/
#include <stdio.h>
#include "client.h"
int main( void ){
FILE *fPtr = fopen("client", "rb+");
struct clientData client = { 0, "", "", 0.0 };
if ( fPtr == NULL){
printf("File could not be opened.\n");
} else {
// request for user's account number
printf("Enter account number"
" ( 1 to 100, 0 to end input )\n?" );
scanf("%d", &client.acctNum);
while ( client.acctNum != 0 )
{
printf("Enter lastname, firstname, balance\n?");
fscanf( stdin, "%s%s%lf", client.lastName, client.firstName, &client.balance);
fseek(fPtr, ( client.acctNum - 1 ) * sizeof( struct clientData), SEEK_SET);
fwrite( &client, sizeof( struct clientData ), 1, fPtr );
printf("Enter account number\n? " );
scanf("%d", &client.acctNum);
}
fclose(fPtr);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment