- 版本
vs2012
- 步骤
手动创建一个ini文件
config.ini
将文件另存为ANSI编码格式,用UTF-8编码,读写中文会出现乱码.
- 源代码
#include <string>
#include <afx.h>
using namespace std;
string A1;
string A2;
string A3;
HMODULE GetSelfModuleHandle()
{
MEMORY_BASIC_INFORMATION mbi;
return ((::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0)
? (HMODULE)mbi.AllocationBase : NULL);
}
CString GetProgramDir()
{
char exeFullPath[MAX_PATH]; // Full path
string strPath = "";
GetModuleFileName(GetSelfModuleHandle(),exeFullPath,MAX_PATH);
strPath=(string)exeFullPath; // Get full path of the file
int pos = strPath.find_last_of('\', strPath.length());
CString path;
path=strPath.substr(0, pos).c_str();
return path;
}
void ini_value()
{
CString szMainKey, StrIniFile;
char szVal[MAX_PATH];
BOOL Ret;
CString DLL_path=GetProgramDir();
StrIniFile=DLL_path+"\config.ini";
szMainKey.Format(_T("CONFIG"));
Ret = GetPrivateProfileString(szMainKey, _T("A1"), _T(""), szVal, MAX_PATH, StrIniFile);
A1 = szVal;
Ret = GetPrivateProfileString(szMainKey, _T("A2"), _T(""), szVal, MAX_PATH, StrIniFile);
A2 = szVal;
Ret = GetPrivateProfileString(szMainKey, _T("A3"), _T(""), szVal, MAX_PATH, StrIniFile);
A3 = szVal;
}
void CMFCApplication1Dlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
//获取当前程序所在目录
CString exe_path = GetProgramDir();
AfxMessageBox(exe_path);
//读取ini
ini_value();
//打印
char msg[256];
sprintf_s(msg, "%s,%s,%s", A1.c_str(), A2.c_str(), A3.c_str());
AfxMessageBox(msg);
}
- 演示
Caesar卢尚宇
2021年2月27日