File: dbfopen.c

package info (click to toggle)
gretl 2022c-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 59,552 kB
  • sloc: ansic: 409,074; sh: 4,449; makefile: 3,222; cpp: 2,777; xml: 599; perl: 364
file content (632 lines) | stat: -rw-r--r-- 18,404 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
   Based on dbfopen.c in Frank Warmerdam's shapelib version 1.5.0
   and modified for use in gretl. Original copyright notice below.
*/

/******************************************************************************
 * Copyright (c) 1999, Frank Warmerdam
 * Copyright (c) 2012-2013, Even Rouault <even dot rouault at mines-paris dot org>
 *
 * This software is available under the following "MIT Style" license,
 * or at the option of the licensee under the LGPL (see COPYING).  This
 * option is discussed in more detail in shapelib.html.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ******************************************************************************
 */

#include "shapefile.h"
#include "libgretl.h"

#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#if defined(WIN32) || defined(_WIN32)
# define STRCASECMP(a,b)         (stricmp(a,b))
#  else
#include <strings.h>
# define STRCASECMP(a,b)         (strcasecmp(a,b))
#endif

#if defined(_MSC_VER)
# if _MSC_VER < 1900
#     define snprintf _snprintf
# endif
#elif defined(WIN32) || defined(_WIN32)
#  ifndef snprintf
#     define snprintf _snprintf
#  endif
#endif

#ifndef FALSE
#  define FALSE 0
#  define TRUE  1
#endif

#define XBASE_FILEHDR_SZ 32
#define XBASE_FLDHDR_SZ  32
#define XBASE_FLDNAME_LEN_READ 11
#define XBASE_FLD_MAX_WIDTH 255

#define HEADER_RECORD_TERMINATOR 0x0D

#define TRIM_DBF_WHITESPACE

/* See http://www.manmrk.net/tutorials/database/xbase/dbf.html */
#define END_OF_FILE_CHARACTER    0x1A

typedef struct DBFInfo_
{
    FILE *fp;
    int nRecords;
    int nRecordLength; /* Must fit on uint16 */
    int nHeaderLength; /* File header length (32) + field
                          descriptor length + spare space.
                          Must fit on uint16 */
    int nFields;
    int *FieldOffset;
    int *FieldSize;
    int *FieldDecimals;
    char *FieldType;
    char *Header; /* Field descriptors */
    int  nCurrentRecord;
    int  bCurrentRecordModified;
    char *CurrentRecord;
    int  nWorkFieldLength;
    char *WorkField;
    int  bNoHeader;
    int  bUpdated;

    union
    {
        double DoubleField;
        int    IntField;
    } fieldValue;

    int  LanguageDriver;
    char *CodePage;
    int  nUpdateYearSince1900; /* 0-255 */
    int  nUpdateMonth; /* 1-12 */
    int  nUpdateDay; /* 1-31 */
    int  bWriteEndOfFileChar; /* defaults to TRUE */
} DBFInfo;

static int DBFLoadRecord (DBFHandle DBF, int iRecord)
{
    if (DBF->nCurrentRecord != iRecord) {
	int nRecordOffset;

	nRecordOffset =
	    DBF->nRecordLength * (size_t) iRecord + DBF->nHeaderLength;

	if (fseek(DBF->fp, nRecordOffset, SEEK_SET) != 0) {
	    gretl_errmsg_sprintf("fseek(%ld) failed on DBF file.",
				 (long) nRecordOffset);
	    return FALSE;
	} else if (fread(DBF->CurrentRecord,
			 DBF->nRecordLength, 1, DBF->fp) != 1) {
	    gretl_errmsg_sprintf("fread(%d) failed on DBF file.",
				 DBF->nRecordLength);
	    return FALSE;
	} else {
	    DBF->nCurrentRecord = iRecord;
	}
    }

    return TRUE;
}

static int DBFGetLenWithoutExtension(const char* Basename)
{
    int i, len = (int) strlen(Basename);

    for (i = len-1;
	 i > 0 && Basename[i] != '/' && Basename[i] != '\\';
	 i--) {
	if (Basename[i] == '.') {
	    return i;
	}
    }
    return len;
}

DBFHandle DBFOpen (const char *Filename, const char *Access)
{
    DBFHandle DBF;
    FILE *pfCPG;
    unsigned char *buf;
    int nFields, nHeadLen, iField;
    char *Fullname;
    int nBufSize = 500;
    int nLenWithoutExtension;

    /* -------------------------------------------------------------------- */
    /*      We only allow the access strings "rb" and "r+".                  */
    /* -------------------------------------------------------------------- */
    if (strcmp(Access,"r") != 0 && strcmp(Access,"r+") != 0
	&& strcmp(Access,"rb") != 0 && strcmp(Access,"rb+") != 0
	&& strcmp(Access,"r+b") != 0)
        return NULL;

    if (strcmp(Access,"r") == 0)
        Access = "rb";

    if (strcmp(Access,"r+") == 0)
        Access = "rb+";

    /* -------------------------------------------------------------------- */
    /*	Compute the base (layer) name.  If there is any extension	*/
    /*	on the passed in filename we will strip it off.			*/
    /* -------------------------------------------------------------------- */
    nLenWithoutExtension = DBFGetLenWithoutExtension(Filename);
    Fullname = malloc(nLenWithoutExtension + 5);
    memcpy(Fullname, Filename, nLenWithoutExtension);
    memcpy(Fullname + nLenWithoutExtension, ".dbf", 5);

    DBF = calloc(1, sizeof(DBFInfo));
    DBF->fp = gretl_fopen(Fullname, Access);

    if (DBF->fp == NULL) {
	memcpy(Fullname + nLenWithoutExtension, ".DBF", 5);
	DBF->fp = gretl_fopen(Fullname, Access);
    }

    memcpy(Fullname + nLenWithoutExtension, ".cpg", 5);
    pfCPG = gretl_fopen(Fullname, "r");
    if (pfCPG == NULL) {
	memcpy(Fullname + nLenWithoutExtension, ".CPG", 5);
	pfCPG = gretl_fopen(Fullname, "r");
    }

    free(Fullname);

    if (DBF->fp == NULL) {
	free(DBF);
	if (pfCPG) fclose(pfCPG);
	return NULL;
    }

    DBF->bNoHeader = FALSE;
    DBF->nCurrentRecord = -1;
    DBF->bCurrentRecordModified = FALSE;

    /* -------------------------------------------------------------------- */
    /*  Read Table Header info                                              */
    /* -------------------------------------------------------------------- */
    buf = malloc(nBufSize);
    if (fread(buf, XBASE_FILEHDR_SZ, 1, DBF->fp) != 1) {
	fclose(DBF->fp);
	if (pfCPG) fclose(pfCPG);
	free(buf);
	free(DBF);
	return NULL;
    }

    // DBFSetLastModifiedDate(DBF, buf[1], buf[2], buf[3]);

    DBF->nRecords =
	buf[4]|(buf[5]<<8)|(buf[6]<<16)|((buf[7]&0x7f)<<24);

    DBF->nHeaderLength = nHeadLen = buf[8]|(buf[9]<<8);
    DBF->nRecordLength = buf[10]|(buf[11]<<8);
    DBF->LanguageDriver = buf[29];

    if (DBF->nRecordLength == 0 || nHeadLen < XBASE_FILEHDR_SZ) {
	fclose(DBF->fp);
	if (pfCPG) fclose(pfCPG);
	free(buf);
	free(DBF);
	return NULL;
    }

    DBF->nFields = nFields = (nHeadLen - XBASE_FILEHDR_SZ) / XBASE_FLDHDR_SZ;

    /* coverity[tainted_data] */
    DBF->CurrentRecord = malloc(DBF->nRecordLength);

    /* -------------------------------------------------------------------- */
    /*  Figure out the code page from the LDID and CPG                      */
    /* -------------------------------------------------------------------- */

    DBF->CodePage = NULL;
    if (pfCPG) {
	size_t n;

	memset(buf, 0, nBufSize);
	if (fread(buf, nBufSize - 1, 1, pfCPG) > 0) {
	    n = strcspn((char *) buf, "\n\r");
	    if (n > 0) {
		buf[n] = '\0';
		DBF->CodePage = malloc(n + 1);
		memcpy(DBF->CodePage, buf, n + 1);
	    }
	}
	fclose(pfCPG);
    }
    if (DBF->CodePage == NULL && buf[29] != 0) {
	snprintf((char *) buf, nBufSize, "LDID/%d", DBF->LanguageDriver);
	DBF->CodePage = malloc(strlen((char *) buf) + 1);
	strcpy(DBF->CodePage, (char *) buf);
    }

    /* -------------------------------------------------------------------- */
    /*  Read in Field Definitions                                           */
    /* -------------------------------------------------------------------- */

    buf = realloc(buf,nHeadLen);
    DBF->Header = (char *) buf;

    fseek(DBF->fp, XBASE_FILEHDR_SZ, 0);
    if (fread(buf, nHeadLen-XBASE_FILEHDR_SZ, 1,
	      DBF->fp) != 1) {
	fclose(DBF->fp);
	free(buf);
	free(DBF->CurrentRecord);
	free(DBF->CodePage);
	free(DBF);
	return NULL;
    }

    DBF->FieldOffset = malloc(sizeof(int) * nFields);
    DBF->FieldSize = malloc(sizeof(int) * nFields);
    DBF->FieldDecimals = malloc(sizeof(int) * nFields);
    DBF->FieldType = malloc(sizeof(char) * nFields);

    for (iField = 0; iField < nFields; iField++) {
	unsigned char *FInfo;

	FInfo = buf + iField * XBASE_FLDHDR_SZ;
	if (FInfo[0] == HEADER_RECORD_TERMINATOR) {
	    DBF->nFields = iField;
	    break;
	}

	if (FInfo[11] == 'N' || FInfo[11] == 'F') {
	    DBF->FieldSize[iField] = FInfo[16];
	    DBF->FieldDecimals[iField] = FInfo[17];
	} else {
	    DBF->FieldSize[iField] = FInfo[16];
	    DBF->FieldDecimals[iField] = 0;

	    /*
	    ** The following seemed to be used sometimes to handle files with long
	    ** string fields, but in other cases (such as bug 1202) the decimals field
	    ** just seems to indicate some sort of preferred formatting, not very
	    ** wide fields.  So I have disabled this code.  FrankW.
	    DBF->FieldSize[iField] = FInfo[16] + FInfo[17]*256;
	    DBF->FieldDecimals[iField] = 0;
	    */
	}

	DBF->FieldType[iField] = (char) FInfo[11];
	if (iField == 0) {
	    DBF->FieldOffset[iField] = 1;
	} else {
	    DBF->FieldOffset[iField] =
		DBF->FieldOffset[iField-1] + DBF->FieldSize[iField-1];
	}
    }

    /* Check that the total width of fields does not exceed the record width */
    if (DBF->nFields > 0 &&
	DBF->FieldOffset[DBF->nFields-1] +
	DBF->FieldSize[DBF->nFields-1] > DBF->nRecordLength) {
	DBFClose(DBF);
	return NULL;
    }

    DBFSetWriteEndOfFileChar(DBF, TRUE);

    return DBF;
}

void DBFClose (DBFHandle DBF)
{
    if (DBF == NULL)
        return;

    fclose(DBF->fp);

    if (DBF->FieldOffset != NULL) {
	free(DBF->FieldOffset);
	free(DBF->FieldSize);
	free(DBF->FieldDecimals);
	free(DBF->FieldType);
    }

    if (DBF->WorkField != NULL)
        free(DBF->WorkField);

    free(DBF->Header);
    free(DBF->CurrentRecord);
    free(DBF->CodePage);

    free(DBF);
}

static void *DBFReadAttribute (DBFHandle DBF, int hEntity, int iField,
			       char chReqType)
{
    unsigned char *Rec;
    void *pReturnField = NULL;

    /* -------------------------------------------------------------------- */
    /*      Verify selection.                                               */
    /* -------------------------------------------------------------------- */
    if (hEntity < 0 || hEntity >= DBF->nRecords)
        return NULL;

    if (iField < 0 || iField >= DBF->nFields)
        return NULL;

    /* -------------------------------------------------------------------- */
    /*	Have we read the record?					*/
    /* -------------------------------------------------------------------- */
    if (!DBFLoadRecord(DBF, hEntity))
        return NULL;

    Rec = (unsigned char *) DBF->CurrentRecord;

    /* -------------------------------------------------------------------- */
    /*      Ensure we have room to extract the target field.                */
    /* -------------------------------------------------------------------- */
    if (DBF->FieldSize[iField] >= DBF->nWorkFieldLength) {
	DBF->nWorkFieldLength = DBF->FieldSize[iField] + 100;
	if (DBF->WorkField == NULL) {
	    DBF->WorkField = malloc(DBF->nWorkFieldLength);
	} else {
	    DBF->WorkField = realloc(DBF->WorkField,
				     DBF->nWorkFieldLength);
	}
    }

    /* -------------------------------------------------------------------- */
    /*	Extract the requested field.					*/
    /* -------------------------------------------------------------------- */
    memcpy(DBF->WorkField,
	   (const char *) Rec + DBF->FieldOffset[iField],
	   DBF->FieldSize[iField]);
    DBF->WorkField[DBF->FieldSize[iField]] = '\0';
    pReturnField = DBF->WorkField;

    /* -------------------------------------------------------------------- */
    /*      Decode the field.                                               */
    /* -------------------------------------------------------------------- */
    if (chReqType == 'I') {
	DBF->fieldValue.IntField = atoi(DBF->WorkField);
	pReturnField = &(DBF->fieldValue.IntField);
    } else if (chReqType == 'N') {
	DBF->fieldValue.DoubleField = atof(DBF->WorkField);
	pReturnField = &(DBF->fieldValue.DoubleField);
    }

    /* -------------------------------------------------------------------- */
    /*      Should we trim white space off the string attribute value?      */
    /* -------------------------------------------------------------------- */
#ifdef TRIM_DBF_WHITESPACE
    else {
	char *pchSrc, *pchDst;

	pchDst = pchSrc = DBF->WorkField;
	while (*pchSrc == ' ')
	    pchSrc++;

	while (*pchSrc != '\0')
	    *(pchDst++) = *(pchSrc++);
	*pchDst = '\0';

	while (pchDst != DBF->WorkField && *(--pchDst) == ' ')
	    *pchDst = '\0';
    }
#endif

    return pReturnField;
}

int DBFReadIntegerAttribute (DBFHandle DBF, int iRecord, int iField)
{
    int	*pnValue;

    pnValue = (int *) DBFReadAttribute(DBF, iRecord, iField, 'I');
    return (pnValue == NULL)? 0 : *pnValue;
}

double DBFReadDoubleAttribute (DBFHandle DBF, int iRecord, int iField)
{
    double *pdValue;

    pdValue = (double *) DBFReadAttribute(DBF, iRecord, iField, 'N');
    return (pdValue == NULL)? 0.0 : *pdValue;
}

const char *DBFReadStringAttribute (DBFHandle DBF, int iRecord, int iField)
{
    return (const char *) DBFReadAttribute(DBF, iRecord, iField, 'C') ;
}

const char *DBFReadLogicalAttribute (DBFHandle DBF, int iRecord, int iField)
{
    return (const char *) DBFReadAttribute(DBF, iRecord, iField, 'L') ;
}

static int DBFIsValueNULL (char chType, const char* Value)
{
    int i;

    if (Value == NULL) {
        return TRUE;
    }

    switch (chType) {
    case 'N':
    case 'F':
	/*
	** We accept all asterisks or all blanks as NULL
	** though according to the spec I think it should be all
	** asterisks.
	*/
	if (Value[0] == '*')
	    return TRUE;

	for (i = 0; Value[i] != '\0'; i++) {
	    if (Value[i] != ' ') {
		return FALSE;
	    }
	}
	return TRUE;
    case 'D':
	/* NULL date fields have value "00000000" */
	return strncmp(Value, "00000000", 8) == 0;
    case 'L':
	/* NULL boolean fields have value "?" */
	return Value[0] == '?';
    default:
	/* empty string fields are considered NULL */
	return strlen(Value) == 0;
    }
}

int DBFIsAttributeNULL (DBFHandle DBF, int iRecord, int iField)
{
    const char	*Value;

    Value = DBFReadStringAttribute(DBF, iRecord, iField);

    if (Value == NULL)
        return TRUE;

    return DBFIsValueNULL(DBF->FieldType[iField], Value);
}

int DBFGetFieldCount (DBFHandle DBF)
{
    return DBF->nFields;
}

int DBFGetRecordCount (DBFHandle DBF)
{
    return DBF->nRecords;
}

/************************************************************************/
/*                          DBFGetFieldInfo()                           */
/*                                                                      */
/*      Return any requested information about the field.               */
/*      FieldName must be at least XBASE_FLDNAME_LEN_READ+1 (=12)    */
/*      bytes long.                                                     */
/************************************************************************/

DBFFieldType
DBFGetFieldInfo (DBFHandle DBF, int iField, char *FieldName,
		 int *pnWidth, int *pnDecimals)
{
    if (iField < 0 || iField >= DBF->nFields)
        return(FTInvalid);

    if (pnWidth != NULL)
        *pnWidth = DBF->FieldSize[iField];

    if (pnDecimals != NULL)
        *pnDecimals = DBF->FieldDecimals[iField];

    if (FieldName != NULL) {
	int i;

	strncpy(FieldName, (char *) DBF->Header + iField*XBASE_FLDHDR_SZ,
		XBASE_FLDNAME_LEN_READ);
	FieldName[XBASE_FLDNAME_LEN_READ] = '\0';
	for (i = XBASE_FLDNAME_LEN_READ - 1; i > 0 && FieldName[i] == ' '; i--) {
	    FieldName[i] = '\0';
	}
    }

    if (DBF->FieldType[iField] == 'L') {
	return FTLogical;
    } else if (DBF->FieldType[iField] == 'D') {
	return FTDate;
    } else if (DBF->FieldType[iField] == 'N'
	       || DBF->FieldType[iField] == 'F') {
	if (DBF->FieldDecimals[iField] > 0
	    || DBF->FieldSize[iField] >= 10) {
	    return FTDouble;
	} else {
	    return FTInteger;
	}
    } else {
	return FTString;
    }
}

/************************************************************************/
/*                       DBFGetNativeFieldType()                        */
/*                                                                      */
/*      Return the DBase field type for the specified field.            */
/*                                                                      */
/*      Value can be one of: 'C' (String), 'D' (Date), 'F' (Float),     */
/*                           'N' (Numeric, with or without decimal),    */
/*                           'L' (Logical),                             */
/*                           'M' (Memo: 10 digits .DBT block ptr)       */
/************************************************************************/

char DBFGetNativeFieldType (DBFHandle DBF, int iField)
{
    if (iField >=0 && iField < DBF->nFields)
        return DBF->FieldType[iField];

    return  ' ';
}

int DBFGetFieldIndex (DBFHandle DBF, const char *FieldName)
{
    char name[XBASE_FLDNAME_LEN_READ+1];
    int i;

    for (i = 0; i < DBFGetFieldCount(DBF); i++) {
	DBFGetFieldInfo(DBF, i, name, NULL, NULL);
	if (!STRCASECMP(FieldName,name))
	    return(i);
    }
    return -1;
}

int DBFIsRecordDeleted (DBFHandle DBF, int iShape)
{
    /* Verify selection */
    if (iShape < 0 || iShape >= DBF->nRecords)
        return TRUE;

    /* Have we read the record? */
    if (!DBFLoadRecord(DBF, iShape))
        return FALSE;

    /* '*' means deleted */
    return DBF->CurrentRecord[0] == '*';
}

const char *DBFGetCodePage (DBFHandle DBF)
{
    return DBF == NULL ? NULL : DBF->CodePage;
}

void DBFSetWriteEndOfFileChar (DBFHandle DBF, int bWriteFlag)
{
    DBF->bWriteEndOfFileChar = bWriteFlag;
}