C語言讀寫ini檔案

2021-06-03 02:41:29 字數 1967 閱讀 3413

其中個引數的意思:

lpctstr lpstring ---------是鍵值,也就是變數的值, 必須為lpctstr或cstring型別

lpctstr lpfilename --------完整的ini檔案路徑名

lpctstr lpdefaut ----------如果沒有其前兩個引數值,則將此值賦給變數

lpstr lpreturnedstring --------接收ini檔案中的值的cstring物件,即接收緩衝區

dword nsize ------接收緩衝區的大小

例子:cstring strname,strtemp;

int nage;

strname = "jacky";

nage = 13;

writeprivateprofilestring("student","name",strname,"c:\\setting.ini");

結果:(ini檔案中顯示如下:)

[student]

name=jacky

讀取:cstring sname;

getprivateprofilestring("student","name","defaultname",sname.getbuffer(max_length),max_length,"c:\\setting.ini");

結果:sname = "jacky";這裡需要注意點就是用完getbuffer函式後一定要釋放(用sname.releasebuffer()函式),不然後面再用到sname的其他子函式就會失靈。

讀整數比較簡單,如下

int result = getprivateprofileint("student","nage",0,"c:\\setting.ini")返回值即為所讀取的結果!

在getprivateprofilestring最後乙個引數是配置檔案路徑的引數,此路徑只能是絕對路徑,不能是相對路徑,但現在我需要是我的exe檔案能和我的配置檔案在一起。因此我使用了getcurrentdirectory函式。

原**如下:

cstring server_ip;

cstring des="";

::getcurrentdirectory(max_pathlength,des.getbuffer(max_pathlength));

des.releasebuffer();

des+="\\config.ini";

getprivateprofilestring("phonedemo","server_ip","",server_ip.getbuffersetlength(15),15,des);

server_ip.releasebuffer();

注意:在這裡使用cstring變數時,在使用完getbuffer後,緊接著一定要使用releasebuffer()函式,才可以進行其他的諸如字串+操作

char m_szcurrpath[255];   

getmodulefilename(::getmodulehandle(null),m_szcurrpath,255);

(_tcsrchr(m_szcurrpath, _t('\\')))[1] = 0; //刪除檔名,只獲得路徑

cstring inipath;

cstring ipaddress;

inipath.format("%sctc.ini",m_szcurrpath);

//讀取ini檔案

getprivateprofilestring("database","ip","ip",ipaddress.getbuffer(255),255,inipath);

下面是ini文件的格式

[section1]

item1=1

[section2]

item2=2

[section3]

item3=3

[section4]

item1=4

item2=0

item3=5

C 讀寫INI檔案

inifile類 using system using system.io using system.runtime.interopservices 因為我們需要呼叫api函式,所以必須建立system.runtime.interopservices命名空間以提供可用於訪問 net 中的 com 物...

C 讀寫INI檔案

using system using system.drawing using system.collections using system.componentmodel using system.windows.forms using system.io using system.runtime...

C 讀寫ini檔案

using system.text using system.runtime.interopservices dllimport kernel32 private static extern long writeprivateprofilestring string section,string k...