C and Databases |
C C C |
|
12C |
|
C C C |
|
C C |
In DBREAD, first the file is opened, then the file header is read into the DB3HEADER structure. The information placed in this structure is used to read the column definitions and the data records.
Next, the program allocates the memory for the column definitions by computing the number of columns:
nColumnCount =
(db3Header.nFirstRecordOffset - sizeof(DB3HEADER)) / sizeof(COLUMNDEF);
The calloc() function uses the nColumnCount variable to allocate the required memory. The column definitions are saved for later use.
ColumnDef = (COLUMNDEF *)calloc(sizeof(COLUMNDEF), nColumnCount);
After the memory is allocated, the column definitions are read. A loop is not necessary; the program uses one read in which the number of bytes is computed from the size of the structure and the number of columns in the database:
nResult = fread((char *)ColumnDef, sizeof(COLUMNDEF), nColumnCount,
DBFile);
After all the columns have been read (determined by the return value from a call to the fread() function), the program can process them as required. In this simple example, the information is printed to the screen. A for() loop is an easy and effective way to process the columns:
for (i = 0; i < nColumnCount; i++)
{
printf(“Name: ‘%10.10s’ “, ColumnDef[i].szColumnName);
When the format of the records has been determined, the program can process the records in the dBASE file. First, a buffer must be allocated to hold the records. The buffer’s size is known (or can be computed from the size of each record, not forgetting the byte for the record’s status):
pBuffer = (unsigned char *)calloc(sizeof(char), db3Header.nRecordLength + 1);
Because we do not use dBASE’s index files, we accept the records in the order that they are stored in the file, using a simple for() loop. Before reading the records, I recommend that you do a seek to the known point where the first record can be found.