Prev  Next  Up  Contents

Adding Records



The iaddrec function is called to add a new record to a database. It requires three arguments, the database handle, an index handle or NULL, and a list of record field values. The field values must be listed in the same order as the corresponding field names passed to the icreate_db function. The iaddrec function returns I_ERROR if an error occurs, or I_OK if the record is successfully added to the database.

The following example program adds a record to the BOOKS database. The user inputs the record field values, each of which is stored in a character array. The record itself is represented by an array of pointers to these field values. The field values must be listed in the same order as the corresponding field names passed to the icreate_db function.

#include 
#include "isam.h"

char author_first[80], author_last[80], book_title[80], isbn_number[80];
char *record[4] = { author_first, author_last, book_title, isbn_number };

int main()                      /* add.c */
{
    Db_Obj *db;
    char   *db_name = "BOOKS";

    /* open existing ISAM database */
    if ((db = iopen_db(db_name)) == NULL) {
        printf("Unable to open database: %s\n", db_name);
        iprterr();
        return -1;
    }

    /* collect record data */
    printf("Enter book title: ");
    gets(book_title);
    printf("Enter author's first name: ");
    gets(author_first);
    printf("Enter author's last name: ");
    gets(author_last);
    printf("Enter 10 digit ISBN number: ");
    gets(isbn_number);

    /* add record to ISAM database */
    if (iaddrec(db, NULL, record) == I_ERROR) {
        printf("Unable to add record to database: %s\n", db_name);
        iprterr();
        return -1;
    }
    printf("\nRecord added to database:\n"
           "\tTitle : %s\n"
           "\tAuthor: %s %s\n"
           "\tISBN  : %s\n",
            book_title, author_first, author_last, isbn_number);

    /* close ISAM database */
    iclose_db(db);

    return 0;
}

Notice that NULL was passed as the second argument to iaddrec. This could optionally have been an index handle returned by the ihandle function. If an index handle is passed to the iaddrec function, then the new record becomes the current record for the associated index. If NULL is passed, then the current record for each index remains unchanged.


Next Page
C/Database Toolchest Description
Product List