Console环境下的ini文件的读写

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不同即可连续写入
 

在C#中,读写INI格式文件非常常见,因为Ini文件结构简单,易于理解和编辑。C#提供了System.Configuration命名空间下的IniSection和IniFile类来处理这种操作。 **读取INI文件:** ```csharp using System; using System.Configuration; public class IniReader { public static void ReadIni(string filePath) { IniFile ini = new IniFile(filePath); if (ini.Exists) { foreach (IniSection section in ini.Sections) { Console.WriteLine("Section Name: " + section.Name); foreach (string key in section.Keys) { string value = section[key]; Console.WriteLine(key + ": " + value); } } } else { Console.WriteLine("File not found."); } } } // 使用示例 IniReader.ReadIni(@"C:\path\to\your.ini"); ``` **写入INI文件:** ```csharp using System; using System.Configuration; public class IniWriter { public static void WriteIni(string filePath, IniSection section) { IniFile ini = new IniFile(); ini.AddSection(section.Name); foreach (KeyValuePair<string, object> keyValue in section) { ini[filePath, section.Name][keyValue.Key] = keyValue.Value.ToString(); } ini.Save(filePath); } // 示例中的section应预先创建或填充好键值对 static void Main() { IniSection mySection = new IniSection("MySection"); mySection["Key1"] = "Value1"; mySection["Key2"] = "Value2"; IniWriter.WriteIni(@"C:\path\to\output.ini", mySection); } } ``` 记得替换上述代码中的`filePath`为实际的ini文件路径。如果你使用的是.Net Core或.Net 6+,可能需要引入`Microsoft.Extensions.FileProviders.Physical`NuGet包来支持物理文件I/O。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值