
Using fread to read data from a database!!
Quote:
>The course I have been doing has covered reading data from text and binary
>files using fscanf, fgets, fread etc.. These all read data until a space, tab,
>newline or EOF is reached but if the file I want to read from is a database do
>I use the same format i.e.
>fread(&order, sizeof(order), 1 , test_ptr);
>*where test_ptr is a pointer to a database file - in this case a microsoft
>excel file.
Patricia, the dBASE type files have a header that is of variable
length and depends on the structure. You need to read in the fixed
portion (as you do above):
#typedef unsigned long ulong
#typedef unsigned short ushort
struct TABLE_HEADER {
char type;
char last_update[3];
ulong records;
ushort first_record;
ushort record_length;
char reserved1[16];
char flags;
char code_page;
char reserved2[2];
Quote:
};
And then you read in this structure one time for every field in the
table:
struct FIELD_RECORD {
char name[10];
char type;
ulong offset;
char length;
char decimals;
char flags;
char reserved[13];
Quote:
};
Note the "ushort first_record" in the table_header. This indicates
where the actual data starts. You'll have to also note that each
record contains a deleted() mark and that will exist at offset 0. So,
in order to get to a particular field offset you'll have to assume
base-1 instead of base-0.
What I do in my code is something like this:
FILE *fh;
struct TABLE_HEADER th;
struct FIELD_RECORD *fptr;
char *buf;
int numread;
fh = fopen("whatever.dbf","rb+");
numread = fread(th, sizeof(th), 1, fh);
if (numread != sizeof(th)) return -1;
buf = malloc(th.first_record - sizeof(th));
if (buf == null) return -1;
numread = fread(buf, th.first_record - sizeof(th), 1, fh);
if (numread != th.first_record - sizeof(th)) return -1;
// Right now, the file is positioned to the first record
// You have read in the table header
// And you have the structure in buf that can be accessed
// using "fptr = (struct FIELD_RECORD *)buf;"
If you have any additional questions, please email me.
- Rick C. Hodgin