- 论坛徽章:
- 0
|
gateway_file.h- #ifndef _GATEWAY_FILE_H_
- #define _GATEWAY_FILE_H_
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct DeviceInfo
- {
- char type[10];
- int id;
- }DeviceInfo;
- FILE *Fopen(char *path);
- int ReadFile(FILE *fp);
- void Fprint(DeviceInfo *di,int len);
- void Fclose(FILE *fp);
- #endif
复制代码 gateway_file.c- #include "gateway_file.h"
- #define USE_DEBUG
- #ifdef USE_DEBUG
- #define DEBUG_ERR(fmt, args...) printf("\033[46;31m[line:%d]\033[0m "#fmt"\r\n",__LINE__, ##args)
- #define DEBUG_INFO(fmt, args...) printf("\033[33m[line:%d]\033[0m "#fmt"\r\n",__LINE__, ##args)
- #else
- #define DEBUG_ERR(fmt, ...)
- #define DEBUG_INFO(fmt, ...)
- #endif
- DeviceInfo *record;
- FILE *Fopen(char *path)
- {
- FILE *fp = fopen(path,"r");
- if(fp == NULL)
- DEBUG_ERR(open file %s failed,path);
- return fp;
- }
- int ReadFile(FILE *fp)
- {
- long len;
- int i = 0;
- char *type=NULL;
- char *id=NULL;
- char buffer[128] = "";
- fseek(fp,0,SEEK_END);
- len = ftell(fp);
- printf("length for ftell in Read = %ld\n",len);
- fseek(fp,0,SEEK_SET);
- record = (DeviceInfo*)malloc(len);
- //memset(record,0,len+40);
- while(fgets(buffer,sizeof(buffer),fp) != NULL)
- {
- type = strtok(buffer," ");
- id = strtok(NULL," ");
- if(type != NULL && id != NULL)
- {
- printf("sizeof type = %d\n",strlen(type));
- printf("sizeof id = %d\n",strlen(id));
- strcpy(record[i].type,type);
- record[i].id = atoi(id);
- i++;
- }
- }
- return i;
- }
- void Fprint(DeviceInfo *di,int len)
- {
- int i;
- printf("length=%d\n",len);
- for(i=0; i<len; i++)
- {
- printf("record[%d].type=%s\t",i,di[i].type);
- printf("record[%d].id=%d\n",i,di[i].id);
- }
- }
- void Fclose(FILE *fp)
- {
- printf("%x\n",fp);
- if(fp != NULL)
- {
- fprintf(stderr,"bug5...\n");
- fclose(fp);
- fprintf(stderr,"bug6...\n");
- }
- }
复制代码 test_read_record.c- #include "gateway_file.h"
- extern DeviceInfo *record;
- int main()
- {
- int length;
- FILE *fp = Fopen("record.txt");
- fprintf(stderr,"bug1...\n");
- length = ReadFile(fp);
- printf("length in test = %d\n",length);
- fprintf(stderr,"bug2...\n");
- Fprint(record,length);
- fprintf(stderr,"bug3...\n");
- free(record);
- fprintf(stderr,"bug4...\n");
- length = ftell(fp);
- printf("length for ftell = %d\n",length);
- Fclose(fp);
- return 0;
- }
复制代码 record.txt
PMAC901 12
PMAC901 12
PMAC901 12
PMAC901 22
PMAC901 32
gateway_file.c封装了读取文件,以及打印数据的一些函数
test_read_record.c为测试文件
gcc test_read_record.c gateway_file.c -o test_read_record
运行./test_read_record,在调用Fclose时,出现段错误
|
|