我想使用vs2019 c++ 读取相对目录下的ini文件
时间: 2023-11-22 16:54:22 浏览: 37
可以使用 Windows API 中的 GetPrivateProfileString 函数来读取 INI 文件。以下是一个简单的示例代码:
```c++
#include <Windows.h>
#include <iostream>
int main() {
// 获取当前可执行文件所在的目录
char path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
std::string dirPath = path;
dirPath = dirPath.substr(0, dirPath.find_last_of('\\'));
// 组合 INI 文件的完整路径
std::string filePath = dirPath + "\\config.ini";
// 读取 INI 文件中的配置项
char buffer[256];
GetPrivateProfileString("SectionName", "KeyName", "", buffer, 256, filePath.c_str());
std::cout << buffer << std::endl;
return 0;
}
```
可以将 INI 文件放置在可执行文件所在的相对目录下,例如此示例中的 config.ini 文件放置在可执行文件所在的同级目录下。
相关问题
我想使用vs2019 使用c++,编写读取ini配置文件的信息
好的,以下是使用 C++ 读取 INI 配置文件的示例代码:
```cpp
#include <iostream>
#include <Windows.h> // 包含 Windows API 函数
int main()
{
// 读取 INI 文件
LPCWSTR path = L"C:\\example.ini"; // INI 文件的路径
WCHAR buffer[1024]; // 缓冲区
DWORD result = GetPrivateProfileString(L"SectionName", L"KeyName", NULL, buffer, 1024, path);
// 参数说明:
// 第一个参数:INI 文件中的 Section 名称
// 第二个参数:INI 文件中的 Key 名称
// 第三个参数:默认值,如果没有找到对应的 Key,则返回默认值
// 第四个参数:输出缓冲区,存储读取到的值
// 第五个参数:缓冲区大小
// 第六个参数:INI 文件的路径
if (result > 0)
{
std::wcout << buffer << std::endl; // 输出读取到的值
}
else
{
std::wcout << L"读取失败!" << std::endl;
}
return 0;
}
```
其中,`GetPrivateProfileString` 是 Windows API 中专门用来读取 INI 文件的函数。需注意的是,该函数只能读取 ANSI 编码和 Unicode 编码的 INI 文件。如果需要读取其他编码格式的 INI 文件,需要使用其他的库或手动解析。
另外,如果 INI 文件中的 Key 值是多个字符串,可以使用 `GetPrivateProfileString` 函数的返回值和输出缓冲区的字符串长度来读取。例如:
```cpp
WCHAR buffer[1024];
DWORD length = GetPrivateProfileString(L"SectionName", L"KeyName", NULL, buffer, 1024, path);
if (length > 0)
{
// 读取到了 Key 值
WCHAR value1[256], value2[256];
swscanf_s(buffer, L"%s %s", value1, _countof(value1), value2, _countof(value2));
// 解析多个字符串
std::wcout << value1 << std::endl;
std::wcout << value2 << std::endl;
}
else
{
// 未找到 Key 值
}
```
以上代码可以读取 INI 文件中的 `KeyName` 值,假设该值为 `"Hello World"`,则会输出:
```
Hello
World
```
其中,`swscanf_s` 是用来解析多个字符串的函数,类似于 `scanf` 函数,但是支持 Unicode 编码。
c++实现读取程序运行目录下的.ini文件
你可以使用以下代码来读取程序运行目录下的.ini文件:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string config_file = "config.ini"; // ini文件名
std::ifstream file(config_file); // 打开文件流
if (file.is_open()) // 检查文件是否打开成功
{
std::string line;
while (std::getline(file, line)) // 逐行读取文件内容
{
std::cout << line << std::endl; // 输出每行内容
}
file.close(); // 关闭文件流
}
else
{
std::cout << "无法打开文件:" << config_file << std::endl;
}
return 0;
}
```
在这个例子中,我们使用`std::ifstream`来打开指定的文件,并且使用`std::getline`逐行读取文件内容。你可以根据需要修改代码来获取你所需的配置信息。