1. 问题描述
config.txt文件内容如下:
expo: [10000]
gain: [2.2]
width: [1280]
height: [1024]
size: [3]
要求:给定一个key(如expo),输出float类型的value(10000)。
参考网址:查找文本文件中的关键字
2. 思路
- 获取.txt文件的长度,即字节数length。
- 开劈一个length+1大小的数组char *text,保存文件数据
- 把文件的内容写到text数组中
- 进行模式串匹配,并返回keyword对应的value在text数组的首尾位置
- 通过value在text数组的首尾位置,为value赋值
- value:char型数组转换为float类型,返回float类型的Fvalue
3. 代码实现
#include <iostream>
#include <fstream>
//获取文件的长度
int GetFileLength(std::ifstream &inputFile)
{
//保存文件当前位置
std::streampos pos = inputFile.tellg();
//定位到文件尾
inputFile.seekg(0, std::ios::end);
//返回文件尾的偏移量,即文件的大小
int length = inputFile.tellg();
//返回到文件先前的位置
inputFile.seekg(pos);
return length;
}
//模式串匹配,得到keyword对应的value在text数组中的首尾位置
int IndexOf(const char *text, int &textSize, const char *match, int matchSize, int &start, int &end)
{
int index = 0;//keyword在text中的位置
for (int i = 0; i <= textSize - matchSize; ++i)
{
int j = 0;
while (j < matchSize && match[j] == text[i + j])
{
++j;
}
//所有的字符都与文本中的一致,则匹配成功
if (j == matchSize)
{
index = i;//找到keyword在text中的位置
//寻找value在text数组中的首尾位置
int k = index;
while (text[k] != '[')
{
k++;
if (text[k] == '[')
{
start = k + 1;
break;
}
}
int t = start;
while (text[t] != ']')
{
t++;
if (text[t] == ']')
{
end = t - 1;
break;
}
}
return 0;
}
}
//匹配失败
return -1;
}
//实现字符串匹配
float getValue(const char *fileName, const char *keyWord)
{
//以只读方式,打开文件fileName
std::ifstream inputFile(fileName);
if (!inputFile)
{
//打开文件失败
std::cout << "error: unable to open input file: " << fileName << std::endl;
return NULL;
}
//获得文件的长度,即字节数,并开劈一个同样大小的数组保存文件数据
int length = GetFileLength(inputFile);
char *text = new char[length + 1];
//把文件的内容写到text数组中
inputFile.read(text, length);
inputFile.close();
text[length] = '\0';
//进行模式串匹配,并返回keyword在text数组的位置
int start = 0;
int end = 0;
IndexOf(text, length, keyWord, strlen(keyWord), start, end);
int valueSize = end - start + 1;
char *value = new char[valueSize];
for (int i = 0; i < valueSize; i++)
{
value[i] = text[start + i];
}
float Fvalue;
Fvalue = atof(value);//char型数组转换为float类型
delete[]text;
delete[]value;
return Fvalue;
}
int main()
{
const char *fileName = "F:/按key获取txt文件的value/config.txt";
const char *keyWord = "size";
float value = getValue(fileName, keyWord);
std::cout << value << std::endl;
system("pause");
return 0;
}
运行结果:
3
请按任意键继续…