中间遇到编码格式问题,导致读取文件的hostName
与字符串hostName
不一致无法进入判断,是cfg文件是uft-8 bom
格式字符串前边多了东西
头文件
#pragma once
//全局配置文件
#ifndef CONFIG_H
#define CONFIG_H
#include <QString>
struct Config
{
QString hostName; //主机名
int Port; //端口
QString DatabaseName ; //数据库
QString userName ; //用户名
QString password; //密码
};
//声明全局变量
extern Config g_config;
//加载配置文件信息
bool loadConfig(const QString& filePath);
#endif
cpp
#include "Config.h"
#include <QFile>
#include <QTextStream>
//只能定义一次
Config g_config;
static QString trim(const QString& str)
{
return str.trimmed();
}
bool loadConfig(const QString& filePath)
{
QFile infile(filePath);
if (!infile.open(QIODevice::ReadOnly | QIODevice::Text))
{
//文件打开失败
return false;
}
QTextStream in(&infile);
while (!in.atEnd())
{
QString line = in.readLine().trimmed();
//跳过空行与注释行
if (line.isEmpty() || line.startsWith('#')) continue;
QStringList parts = line.split("=", Qt::SkipEmptyParts);
if (parts.size() != 2) continue;
QString key = parts[0].trimmed().remove(QChar(0xFEFF)); // 去除 UTF-8 BOM;
QString value = parts[1].trimmed().remove(QChar(0xFEFF));
if (key == "hostName")
{
g_config.hostName = value;
}
else if (key == "Port") g_config.Port = value.toInt();
else if (key == "DatabaseName") g_config.DatabaseName = value;
else if (key == "userName") g_config.userName = value;
else if (key == "password") g_config.password = value;
}
infile.close();
return true;
}
在main.cpp里调用加载cfg,即可以在整个项目中使用g_config.变量名
if (!loadConfig("config.cfg")) {
Log::getInstance()->appendLog("配置文件加载失败");
}
config.cfg文件
#数据库配置
hostName = localhost
Port = 3306
DatabaseName = ocr
userName = root
password = 123456