如何使用C++读取ini文件并进行备份
#include
#include
#include
#include
using namespace std;
int main()
{
// 读取ini文件
string file_path = "file.ini"; //文件路径,请自行修改
string current_dir = GetCurrentDir(); //获取当前目录
string full_file_path = current_dir + '\\' + file_path; //拼接完整路径
ifstream in(full_file_path.c_str());
if (!in.is_open())
{
cout << "文件打开失败" << endl;
return -1;
}
// 备份ini文件
string bak_file_path = "file_backup.ini"; //备份文件路径,请自行修改
string bak_full_file_path = current_dir + '\\' + bak_file_path; //拼接完整路径
ofstream out(bak_full_file_path.c_str());
if (!out.is_open())
{
cout << "备份文件创建失败" << endl;
return -1;
}
string line;
while (getline(in, line))
{
out << line << endl;
}
in.close();
out.close();
cout << "备份成功" << endl;
return 0;
}
string GetCurrentDir()
{
char exeFullPath[MAX_PATH];
GetModuleFileName(NULL, exeFullPath, MAX_PATH);
string strPath = (string)exeFullPath;
int pos = strPath.find_last_of('\\', strPath.length());
return strPath.substr(0, pos);
}
用户评论