问题:
今天将_public.h/_public.c 复制为_public.h/_public.cpp,用g++编译出错。
gcc和g++之间的“恩怨”先不谈… …
解决方法先记录一下。
一、xml解析函数
c代码:
//解xml字符串函数
#include <stdio.h>
#include <string.h>
int GetXMLBuffer(const char *in_XMLBuffer,const char *in_FieldName,char *out_Value);
struct st_girl
{
char name[50];
int age;
char sc[30];
char yz[30];
};
void GetXMLValue(const char *in_XMLBuffer,struct st_girl *pst);
int main()
{
struct st_girl stgirl;
char strXMLBuffer[301];
//char strValue[51];
memset(strXMLBuffer,0,sizeof(strXMLBuffer));
strcpy(strXMLBuffer,"<name>西施</name><age>18</age><sc>火辣</sc><yz>漂亮</yz>");
GetXMLValue(strXMLBuffer,&stgirl);
printf("name=%s\n",stgirl.name);
printf("age=%d\n",stgirl.age);
printf("sc=%s\n",stgirl.sc);
printf("yz=%s\n",stgirl.yz);
}
//<name>西施</name><age>18</age>
int GetXMLBuffer(const char *in_XMLBuffer,const char *in_FieldName,char *out_Value)
{
char b_fieldname[12],e_fieldname[12];
memset(b_fieldname,0,sizeof(b_fieldname));
memset(e_fieldname,0,sizeof(e_fieldname));
sprintf(b_fieldname,"<%s>",in_FieldName);
sprintf(e_fieldname,"</%s>",in_FieldName);
//printf("%s\n",b_fieldname);
//printf("%s\n",e_fieldname);
char *bpos,*epos;
bpos=epos=0;
bpos=strstr(in_XMLBuffer,b_fieldname);
epos=strstr(in_XMLBuffer,e_fieldname);
if( (bpos==0) || (epos==0) ) return -1;
//<name>西施</name>18</age><sc>火辣</sc><yz>漂亮</yz>
strncpy(out_Value,bpos+strlen(b_fieldname),epos-bpos-strlen(b_fieldname));
return 1;
}
void GetXMLValue(const char *in_XMLBuffer,struct st_girl *pst)
{
memset(pst,0,sizeof(struct st_girl));
//memset(pst,0,sizeof(pst));//指针的sizeof是8个字节,所以不能用
GetXMLBuffer(in_XMLBuffer,"name",pst->name);
char str[10];
GetXMLBuffer(in_XMLBuffer,"age",str);
pst->age=atoi(str);
GetXMLBuffer(in_XMLBuffer,"sc",pst->sc);
GetXMLBuffer(in_XMLBuffer,"yz",pst->yz);
}
gcc编译通过。
g++编译报错:
添加头文件:
#include <stdlib.h>
72行错误消失:
53/54类型转换问题:强制转换为(char *)
bpos=(char *)strstr(in_XMLBuffer,b_fieldname);
epos=(char *)strstr(in_XMLBuffer,e_fieldname);
二、创建子目录
c代码:
//创建子目录
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int MKDIR(const char *pathname);
int main(int argc,char *argv[])
{
MKDIR(argv[1]);
}
int MKDIR(const char *pathname)
{
char strpathName[301];
int i;
for(i=1;i<strlen(pathname);i++)
{
if(pathname[i] != '/') continue;
memset(strpathName,0,sizeof(strpathName));
strncpy(strpathName,pathname,i); //逐级创建子目录,所以是i
printf("name=%s\n",strpathName);
if(access(strpathName,F_OK) ==0 ) continue;
if(mkdir(strpathName,00755) !=0 ) return -1;
}
}
gcc编译通过。
g++编译报错:
添加头文件:
#include <sys/stat.h>
g++编译通过。