读书人

help:dbf文件读取出有关问题

发布时间: 2012-09-05 15:19:34 作者: rapoo

help:dbf文件读取出问题
以下代码有一个部分不正常输出.请指点!
有问题部分我在程序用中注释注释了问题.谢谢指教!!!!
//main.cpp
C/C++ code#include "main.h"

HANDLE hOut;
struct dbf_head temp_head;//定义文件头
struct dbf_field temp_field;//定义文件字段

unsigned long rec_length = 0;//记录个数
unsigned long head_lendth = 0;//文件头长度
unsigned long rec_size = 0;//每条记录长度
unsigned long fieldnum = 0;//字段个数
void main()
{
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD scrsize;
scrsize.X = 2000;
scrsize.Y = 2000;
SetConsoleScreenBufferSize(hOut,scrsize);
//head_mes();
//field_msg();
readtext();
CloseHandle(hOut);

}

void readtext()
{
FILE* pf;
char fname[20];
puts("请输入文件名:");
gets(fname);
strcat(fname,".xls");
pf = fopen(fname,"rb");
if(pf == NULL)
{
printf("打开文件%s失败!",fname);
return ;
}

fread(&temp_head,sizeof(temp_head),1,pf);
//记录总长
rec_length = temp_head.last_rec[0] + temp_head.last_rec[1]*0x100
+ temp_head.last_rec[2]*0x10000 + temp_head.last_rec[3]*0x1000000;
//头总长
head_lendth = temp_head.data_offset[0] + temp_head.data_offset[1]*0x100;
//每条记录长
rec_size = temp_head.rec_size[0] + temp_head.rec_size[1]*0x100;

unsigned long i = 0;
char temp[300];//存放每条记录并输出
fseek(pf,head_lendth,SEEK_END);//将文件指针放到记录开始位置
memset(temp,0,300);
while(i<rec_length)//读记录,打印
{
i++;
fgets(temp,rec_size+1,pf);//此部分temp始终为空.请问为什么?要如何处理. printf("记录%u:%s\n",i,temp);//我的用意是一下子读一个记录.然后输出.
}
fclose(pf);//
}

//main.h
C/C++ code#ifndef H_H_MAIN
#define H_H_MAIN
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <wincon.h>
//函数
void head_mes();//文件头信息
void field_msg();//文件字段信息
void readtext();//文件内容
//变量及结构
extern HANDLE hOut;
//DBF文件头
struct dbf_head
{
char dbf_id;//03H表示无备注;83H表示有备注
char last_update[3];//上次更改数据文件的时间年、月、日
// long last_rec;//用来记录最后一个数据项的号码,即数据记录的条数;
unsigned char last_rec[4];
// unsigned data_offset;//记录程序的真正起始地址
// unsigned rec_size;//记录的长度
unsigned char data_offset[2];
unsigned char rec_size[2];
char filler[20];//保留
};
//DBF文件字段
struct dbf_field
{
char field_name[11];//字段名
char field_type;//字段类型
char field_addr[4];//字段在内存的地址
union//长度信息
{
unsigned char len;
struct
{
char len;//长度
char dec;//小数位数
}num_size;
}len_info;
char field_filler[14];//保留
};


extern struct dbf_head temp_head;//定义文件头
extern struct dbf_field temp_field;//定义文件字段

extern unsigned long rec_length;//记录个数
extern unsigned long head_lendth;//文件头长度
extern unsigned long rec_size;//每条记录长度
extern unsigned long fieldnum;//字段个数
#endif

[解决办法]
dbf文件不是文本文件,每条记录之间不是用回车分隔,而是定长。
所以你不应该用fgets,而应该用fread,每次读rec_size。
[解决办法]
所谓temp是空的,是因为你用printf+%s来显示temp是不行的。temp不是字符串。它是一个地址,在这个地址里顺序排列各个字段的值,你需要根据头部field信息来解析temp开始,长度为rec_size的地址段的内容。

------解决方案--------------------


fseek(pf,head_lendth,SEEK_END);//将文件指针放到记录开始位置

SEEK_END你确定这是开始?我怎么记得这是文件末尾啊

文件末尾当然是空的啦SEEK_BEGIN看样子也像点啊

读书人网 >VC/MFC

热点推荐