背景:主机上table.xml文件定义了业务处理要用的表项,主机需要将该xml文件内容传递给应用程序。由于看代码发现有现成的函数将主机内存中的数据生成xml文件。如下
include <stdio.h>
2 void str2xml(char *pTable)//pTable指向内存中的xml字符
3 {
4 FILE *fd;
5 fd = fopen("/home/table.xml","aw+");//在home目录下创建table.xml文件
6 if (fd)
7 {
8 fputs(pTable,fd);
9 }
10 fclose(fd);
11 return ;
12 }
要实现的是逆过程,查看C语言的文件操作函数,对应fputs的从字面看应该是fgets,于是Ctrl C,Ctrl V写了如下代码;
#include <stdio.h>
14 #define XML_FILE_MAX_SIZE 102400
15 void xml2str(char *pTable)
16 {
17 FILE *fd;
18 fd = fopen("/home/table.xml","r");//打开home目录下的table.xml文件
19 if (fd)
20 {
21 fgets(pTable,XML_FILE_MAX_SIZE,fd);//table.xml文件读入pTable
22 }
23 fclose(fd);
24 return ;
25 }
花半小时编译(工程比较大),再花半小时装载到设备&启动。
gdb调试发现table.xml只有首行写入pTable了。进一步man fgets才发现“char *fgets(char *s, int size, FILE *stream); reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.” 于是修改如下
#include <stdio.h>
14 #define XML_FILE_MAX_SIZE 102400 //XML文件最大size
15 #define BUFF_SIZE 100
16 void xml2str(char *pTable)
17 {
18 FILE *fd;
19 char buff[BUFF_SIZE];
20 int i = 1;
21 char * pcTemp = pTable;
22 fd = fopen("/home/table.xml","r");
23 if (fd)
24 {
25 while(fgets(buff,BUFF_SIZE,fd) != NULL)//fgets读到还行符号或者EOF即停止,如果文件是多行的,每次只读一行
26 {
27 strncpy(pcTemp,buff,BUFF_SIZE);
28 printf("line[i++]:%s",pcTemp);
29 pcTemp += strlen(buff);
30 }
31 }
32 fclose(fd);
33 return ;
34 }
调试发现,有些行不能输出,定位发现xml文件的某些行多于150个字符,修改扩大BUFF_SIZE 解决。通过这番折腾,经验注意害死人啊,先想清楚再动手。