Skip to content

Instantly share code, notes, and snippets.

@tuldok89
Created July 4, 2012 12:53
Show Gist options
  • Save tuldok89/3047192 to your computer and use it in GitHub Desktop.
Save tuldok89/3047192 to your computer and use it in GitHub Desktop.
DBFZ Test
#include <stdio.h>
#include <string.h>
#include "dbfz.h"
record new_record(char *name, char *section, char *address)
{
record nr;
memset(&nr, 0, sizeof(record));
sprintf(nr.name, "%s", name);
sprintf(nr.address, "%s", address);
sprintf(nr.section, "%s", section);
return nr;
}
void write_records(record array[], int num_records)
{
FILE *fp = fopen("file.db", "w");
dbheader header;
sprintf(header.magic, "%s", MAGIC);
header.num_records = num_records;
fwrite(&header, sizeof(dbheader), 1, fp);
fwrite(array, sizeof(record), num_records, fp);
fflush(fp);
fclose(fp);
}
RESULT read_records(record array[], int* num_records)
{
FILE *fp = fopen("file.db", "r");
dbheader header;
fread(&header, sizeof(dbheader), 1, fp);
if (strcmp(header.magic, MAGIC) == 0) // check if it's the right file
return FAIL;
*num_records = header.num_records;
fread(array, sizeof(record), *num_records, fp);
fclose(fp);
return OK;
}
#ifndef DBFZ_H
#define DBFZ_H
#define MAGIC "DBFZ"
#define OK 1
#define FAIL 0
#define RESULT int
typedef struct _record
{
char name[50];
char section[15];
char address[255];
} record;
typedef struct _dbheader
{
char magic[4];
int num_records;
} dbheader;
record new_record(char *name, char *section, char *address);
void write_records(record array[], int num_records);
RESULT read_records(record array[], int* num_records);
#endif // DBFZ_H
#include <stdio.h>
#include <stdlib.h>
#include "dbfz.h"
int main(int argc, char *argv[])
{
record yy[4];
int i;
record in[255];
int numread;
yy[0] = new_record("Marilyn J. Monroe",
"BSCS-42E1",
"52 National Highway, Bayanan, Muntinlupa City");
yy[1] = new_record("Eduard Tudor",
"BSCS-31A1",
"64 Summitville Ave., Putatan, Muntinlupa City");
yy[2] = new_record("Lalaine B. Bagui",
"BSBA-32A1",
"6401A Commonwealth Ave., Project 8, Quezon City");
yy[3] = new_record("Selena Luna A. Valdez",
"BSCS-42E1",
"8 India St., Better Living Subd., Don Bosco, Paranaque City");
write_records(yy,4);
read_records(in, &numread);
for (i = 0; i < numread; i++)
{
printf("Student: %s\n", in[i].name);
printf("Section: %s\n", in[i].section);
printf("Address: %s\n\n", in[i].address);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment