Create database using file operation in c language

cdatabasefile handling

I have created a database using files. When inserting a record in the file if the record already exists in the file, it will end up being duplicated. But I want to avoid that. How can I design a mechanism to avoid duplicating records (i.e., how to check if the record is already in the file and how to stop the same data being entered again by user in the file)?

/*  vehicle record program      */

#include <stdio.h>
#include <string.h>

typedef struct vehicle
{
    char name[100];
    int lice_no;
    int vehicle_type;
    char cmpny_name[100];
    int menu_year;
}record;

int main(void)
{
    int i , choice;
    FILE *fp1,*fp2;
    char oname[100];
    record det;
    int recsize;
    char c;

    fp1 = fopen("record.dat" , "r+");
    if(fp1 == NULL)
    {
        fp1 = fopen("record.dat" , "w+");
        if(fp1 == NULL)
        {
            printf("error in opening file : \n");
            return -1;
        }
    }
    recsize = sizeof(det);

    fseek(fp1 , 0 ,SEEK_END);
    printf("Enter owner Name    : ");
    scanf("%[^\n]" , det.name);
    printf("Enter licence number    : ");
    scanf("%d" , &det.lice_no);
    printf("Enter the vehicle type  : ");
    scanf("%d" , &det.vehicle_type);
    scanf("%c" , &c);
    printf("Enter company name  : ");
    scanf("%[^\n]" , det.cmpny_name);
    printf("Enter menufecture year  : ");
    scanf("%d" , &det.menu_year);
    fwrite(&det,recsize,1,fp1);
}

Best Answer

Before inserting a new record, you must check whether the same record is already in the file. In order to do that, I would start by creating several functions. Something like:

void find_record(char *name, record *rec, FILE *f);
void add_record(const record *rec, FILE *f);
void del_record(char *name, FILE *f);

I am assuming that name alone identifies a given record. Otherwise, you will need to use a composite key (e.g., name + lice_no).

Once you have all those functions, preventing a duplicate record becomes much easier:

void add_record(const record *rec, FILE *f) {
    ...
    record *r;
    find_record(rec->name, r, f);
    if (r == NULL) {
        // record is not already in the file -> insert it
        ...
    }
    else {
        // record is already in the file -> do nothing
        printf("A record with name %s already exists\n", r->name);
    }
    ...
}

As you can see, programming in a modular way really helps a lot, and makes things much easier.