C Language Development Kit/Snippets/Database/InsertionSort

From OptiWiki

< C Language Development Kit | Snippets | Database
Revision as of 13:03, 10 July 2009 by Jbo (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Description Sort the file with insertion sort method. Insertion sort is a very good sort algorithm for an almost sorted database.
int InsertionSort( SDBFile *dbFile, short offset, short checksize );
Arguments SDBFile *dbFile

dbFile is pointer to a structure that holds information about the database. The SDBFile structure is defined as followed:

typedef struct
    short  sRecSz;        // record size of database
    int    fd;            // real handle to the open file
    long   lCurrRecord;   // current record number
    long   lTotalRecords; // total amount of records
    int    bOpen;         // check to see if db is open or closed
short offset

Start from what position in record sorting. When offset is 0 then sorting is started from the first position in the record.

short checksize

Length of sorting part of database e.g. EAN8 is only 8 characters.

TRUE On success.
FLASE On failure.
Remarks The declaration of the SDBFile needs to be static to make sure all items are initialized to 0.

When the InsertionSort() functions returns FALSE the error code can be obtained by making a call to GetDBErrorCode() function.

#include "lib.h"
#include <stdio.h>
#include <stdlib.h>
#include "database.h"  //Holds the database functions
void main( void )
    static SDBFile dbFile; // static initializes all items to 0
    long recno;
    int i;
    char record[32 + 1];
    printf("\fCreate database\n");
    if( !CreateDatabase("file1.txt", 32, &dbFile ))
        printf("Error code = %ld\n", GetDBErrorCode());
    memset( record, '\0', sizeof( record ));
    printf("Write 10 records\n");
    for( i = 9; i > -1; i-- )
        sprintf(record, "%01d23456789012345678901234567890\r\n", i);
        if( !WriteRecord( &dbFile, record, WRITE_APPEND ))
            printf("Error code = %ld\n", GetDBErrorCode());
    if( !InsertionSort( &dbFile, 0, 2 ))
        printf("Error code = %ld\n", GetDBErrorCode());
    if( ReadFirstRecord( &dbFile, record ))
        printf("%-30.30s\n", record );
        while( GetCurrentRecord( &dbFile ) < ( GetTotalRecords( &dbFile ) -1L))
            if( !ReadNextRecord( &dbFile, record ) )
                printf("Error code = %ld\n", GetDBErrorCode());
            printf("%-30.30s\n", record );
        printf("Error code = %ld\n", GetDBErrorCode());
    printf("Close database\n");
    CloseDatabase( &dbFile );
    while( 1 )

Personal tools