ini文件的读写问题,搞了一下午终于弄好了,纠结呀~~~~~
一般ini文件读写都是在mfc中完成的,这次要在Console环境中实现。在网上找了好久,都是东抄西抄的,都一样。。。而且都是在mfc下实现的,看来写东西的人越来越少了,让人心寒呀,最可悲的是,转载人家的还大言不惭的写着原创。nm都这么巧,跟人家创的一样。。。。。。废话不多说了。
好了,现在把自己学到的ini读写与大家分享下。
在Console环境中如果头文件写入#include "afx.h";程序会报错,这里需要设置下编译器,我用的是vs2008,项目-属性-常规-mfc的使用,使用mfc。如图:
之后再加入#include "afx.h";头文件就没问题了;下面把代码给大家分享:
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "afx.h"
#include <string>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//写入字符串
WritePrivateProfileString(_T("StudentInfo"),_T("Name"),_T("leeboy"),_T("d:\\student.ini"));
//数字也以字符串的形式写入
WritePrivateProfileString(_T("StudentInfo"),_T("Age"),_T("22"),_T("d:\\student.ini"));
//读取字符串
CString strStudName;
GetPrivateProfileString(_T("StudentInfo"),_T("Name"),_T("默认姓名"),
strStudName.GetBuffer(MAX_PATH),MAX_PATH,_T("d:\\student.ini"));
//读取整数
int Result = GetPrivateProfileInt(_T("StudentInfo"),_T("Age"),0,_T("d:\\student.ini"));
wcout << (LPCTSTR)strStudName << endl;//Console环境中CString的输出
//wcout << strStudName.GetString() << endl;
cout << Result;//输出数字
system("pause");
return 0;
}
只要组名如StudentInfo不同即可连续写入