CPP读取dbf文件

prop系统导出的交收数据为dbf文件格式,linux需要能够解析该格式文件,

找到一个开源库shapelib可以实现该功能;

1、下载库源码

http://download.osgeo.org/shapelib/

选择shapelib-1.4.0.zip这个版本;

2、解压下载的源码,编译,

[fm@vm178 dbf_demo]$ ./configure --prefix=/home/fm/dbf_demo/shapelib

此时会在源码目录生成MakeFile文件,注意修改以下地方

目的是不让编译contrib目录下面的例子代码,编译会报错;

执行 make & make install

源码编译安装完成;

3、编写测试例子代码:

[fm@vm178 dbf_demo]$ g++ -o test test.cpp -I ./shapelib/include/ -L ./shapelib/lib/ -lshp

test.cpp代码如下:

#include <stdlib.h>
#include <string.h>
#include "shapefil.h"

int main( int argc, char ** argv )

{
DBFHandle    hDBF;
int        *panWidth, i, iRecord;
char    szFormat[32], szField[1024];
char    ftype[32], cTitle[32], nTitle[32];
int        nWidth, nDecimals;
int        cnWidth, cnDecimals;
DBFHandle    cDBF;
DBFFieldType    hType,cType;
int        ci, ciRecord;

/* -------------------------------------------------------------------- */
/* Display a usage message. */
/* -------------------------------------------------------------------- */
if( argc != 2 )
{
    printf( "dbfinfo xbase_file\n" );
    exit( 1 );
}

/* -------------------------------------------------------------------- */
/* Open the file. */
/* -------------------------------------------------------------------- */
hDBF = DBFOpen( argv[1], "rb" );
if( hDBF == NULL )
{
    printf( "DBFOpen(%s,\"r\") failed.\n", argv[1] );
    exit( 2 );
}

printf ("Info for %s\n",argv[1]);

/* -------------------------------------------------------------------- */
/*    If there is no data in this file let the user know.        */
/* -------------------------------------------------------------------- */
i = DBFGetFieldCount(hDBF);
printf ("%d Columns, %d Records in file\n",i,DBFGetRecordCount(hDBF));

/* -------------------------------------------------------------------- */
/*    Compute offsets to use when printing each of the field         */
/*    values. We make each field as wide as the field title+1, or     */
/*    the field value + 1.                         */
/* -------------------------------------------------------------------- */
panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) );
    
    //
按行读取
    for( i = 0; i < DBFGetRecordCount(hDBF); i++ )
{
        for( int j = 0; j < DBFGetFieldCount(hDBF); j++ )
        {
            const char * pszVal = DBFReadStringAttribute( hDBF, i, j);
            printf ("%s\n",pszVal);
        }
}
DBFClose( hDBF );
return( 0 );
}

posted @ 2018-10-16 11:26  Mr.R123  阅读(292)  评论(0编辑  收藏  举报