[C++基础]一个比较常用的配置文件初始化文件读取程序
[C++基础]⼀个⽐较常⽤的配置⽂件初始化⽂件读取程序
在编程中,我们经常会遇到⼀些配置⽂件或初始化⽂件。这些⽂件通常后缀名为.ini或者.conf,可以直接⽤记事本打开。⾥⾯会存储⼀些程序参数,在程序中直接读取使⽤。例如,计算机与服务器通信,服务器的ip地址,段⼝号可以存储于ini⽂件中。这样如果我想换另外⼀台服务器时,直接将ini⽂件中的ip地址改变即可,程序源代码不需要做任何修改。
本⽂将分享⼀段常⽤代码,⽤于读取配置⽂件中的信息。本⽂中的代码为C语⾔编写,在ubuntu 12.04 linux系统中调试没有问题。具体操作如下:
1. ⾸先⽤记事本创建⼀个config.ini⽂件(⽂件名可以随便取),并假设该⽂件是我们要读取的配置⽂件。⽂件内容如下:
information1: 1234567890
information2: this is test information
information3: `~!@#$%^&*()_+{}-[]\|:"/.,<>
假设我们读取的初始化⽂件每⼀⾏都是  <;属性名称>: <;属性值>  的格式。在上述例⼦中,⽂件共有三⾏,分别代表三个属性的信息。
如何提升营业额2. 然后就是我们的代码⽂件了,如下(将以下代码存在ReadFile.cpp中):
#include <string.h>
#include <stdio.h>
const size_t MAX_LEN = 128;
typedef struct{
char firstline[MAX_LEN];
char secondline[MAX_LEN];
char thirdline[MAX_LEN];
} Data;
void readfile(Data *d){
const char *FileName = "config.ini";
char LineBuf[MAX_LEN]={0};
FILE *configFile = fopen(FileName, "r");
memset(d,0,sizeof(Data));
while(NULL != fgets(LineBuf, sizeof(LineBuf), configFile))
{
size_t bufLen = strlen(LineBuf);
if('\r' == LineBuf[bufLen-1] || '\n' == LineBuf[bufLen-1])
{
LineBuf[bufLen-1] = '\0';
}
char *pos = strchr(LineBuf,':');
if(NULL != pos)
{
*pos = '\0';
凿壁偷光的含义pos++;
if(0 == strcmp(LineBuf, "information1"))
{
for(; *pos == ''; pos++){}
strcpy(d->firstline, pos);
}
隆力奇蛇油膏else if(0 == strcmp(LineBuf, "information2"))
{
for(; *pos == ''; pos++){}
strcpy(d->secondline, pos);
}
else if(0 == strcmp(LineBuf, "information3"))
{
for(; *pos == ''; pos++){}
strcpy(d->thirdline, pos);
}
else
{
printf("Failed to read information from the file.");
break;
}
能让下面滴水到爆的说说
}
}
fclose(configFile);
configFile = NULL;
return;
}
int main(int argc, char *argv[])
{
Data *d = new Data;
readfile(d);
printf("d->firstline is \"%s\"\n", d->firstline);
printf("d->secondline is \"%s\"\n", d->secondline);
printf("d->thirdline is \"%s\"\n", d->thirdline);
delete d;
return0;
eva拼图地垫}
其中,struct Data是⽤于存储要读取的信息的结构体,readfile函数也就是实现我们读取功能的函数,其中的值均存在struct Data中。最后我们写了⼀个简单的main函数⽤来测试结果。需要注意的是,在struct Data中,我们设置了char数组长度,最⼤不超过128。因此如果要读取的信息超过128字节可能会出错。如果有需要读取更长的话可以将MAX_LEN设置为⼀个更⼤的值。
3. 最后就是我们的调试结果了,在命令⾏中运⾏如下命令
$ g++ -o test.out ReadFile.cpp
私家车年限$ ./test.out
然后就是运⾏结果:
d->firstline is "1234567890"
d->secondline is "this is test information"
d->thirdline is "`!@#$%^&*()_+{}-[]\|:"/.,<>"
这种读取⽂件的代码应该⾮常常⽤,要掌握。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。