linux配置文件如何写,linux读写配置文件

这是一个C++实现的从文件中读取并获取指定section和item的配置字符串的函数。函数通过ifstream处理文件流,查找指定section,然后在该section内找到目标item,并返回其值。如果找不到相应项,则返回错误。
摘要由CSDN通过智能技术生成

#include "cstdio"

#include "iostream"

#include "string"

#include "fstream"

using namespace std;

int GetProfileString(string file_name, string section_name, string item_name,

string &item_value)

{

ifstream mystream ;

mystream.open(file_name.c_str(), ios::in);

if (!mystream)

{

cout << "Error " << endl;

return -1;

}

char line[30] = {0};

string line2;

string::size_type return_of_find;

bool found = false;

while (mystream.getline(line, 30) && !found) //默认行不会超过30个字符

{

line2 = line;

return_of_find = line2.find(section_name);

if (string::npos == return_of_find)

continue; //没找到section项,则继续下⼀行读取

//找到了,则执行第二步,寻找相应的键值,关键是不能跨越多段

while (mystream.getline(line, 30) && !found)

{

line2 = line;

string equal_flag = "=";

return_of_find = line2.find(equal_flag);

if (string::npos == return_of_find)

return -1;//说明已经跨越了多段,目标寻找失败

//还在当前段中

return_of_find = line2.find(item_name);

if (string::npos == return_of_find)

continue; //没有找到

//找到了

return_of_find = line2.rfind(" "); //要求配置文件=两边要有空格

item_value = line2.substr(return_of_find + 1); //该行最后一个空格之后开始的为所要的item_value

found = true;

}

}

mystream.close();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值