INI檔案程式設計

2021-06-15 22:49:15 字數 2191 閱讀 8635

在我們寫的程式當中,總有一些配置資訊需要儲存下來,以便完成程式的功能,最簡單的辦法就是將這些資訊寫入ini檔案中,程式初始化時再讀入.具體應用如下:

一.將資訊寫入.ini檔案中.

1.所用的winapi函式原型為:

bool writeprivateprofilestring

(lpctstr lpkeyname,

lpctstr lpstring,

lpctstr lpfilename

);其中各引數的意義:

lpctstr lpstring 是鍵值,也就是變數的值,不過必須為lpctstr型或cstring型的.

lpctstr lpfilename 是完整的ini路徑加檔名.

2.具體使用方法:設現有一名學生,需把他的姓名和年齡寫入 c:/stud/student.ini 檔案中.

cstring strname;

strname="張三";

writeprivateprofilestring("studentinfo","name",strname,"c://stud");

此時c:/stud/student.ini檔案中的內容如下:

[studentinfo]

name=張三

二.將資訊從ini檔案中讀入程式中的變數.

1.所用的winapi函式原型為:

dword getprivateprofilestring

(lpctstr lpkeyname,

lpctstr lpdefault,

lptstr lpreturnedstring,

dword nsize,

lpctstr lpfilename

); 其中各引數的意義:

前二個引數與 writeprivateprofilestring中的意義一樣.

lpctstr lpdefault : 如果ini檔案中沒有前兩個引數指定的欄位名或鍵名,則將此值賦給變數.

lptstr  lpreturnedstring : 接收ini檔案中的值的cstring物件,即目的快取器.

dword   nsize : 目的快取器的大小.

lpctstr lpfilename : 是完整的ini檔名.

2.具體使用方法:現要將上一步中寫入的資訊讀入程式中.

cstring strstudname;

getprivateprofilestring("studentinfo","name","預設姓名",strstudname.getbuffer(max_path),max_path,"c://stud");

執行後 strstudname 的值為:"張三",若前兩個引數有誤,其值為:"預設姓名".

3.讀入整型值要用另乙個winapi函式:

uint getprivateprofileint

(lpctstr lpkeyname,

int ndefault,

lpctstr lpfilename

); 這裡的引數意義與上相同.使用方法如下:

nstudage=getprivateprofileint("studentinfo","age",10,"c://stud");

補充幾點:

1.ini檔案的路徑必須完整,檔名前面的各級目錄必須存在,否則寫入不成功,該函式返回 false 值.

2.檔名的路徑中必須為 // ,因為在vc++中, // 才表示乙個 / .

3.也可將ini檔案放在程式所在目錄,此時 lpfilename 引數為: ".".

[dllimport("kernel32")]

private static extern long writeprivateprofilestring(string

section, string key, string val, string filepath);

[dllimport("kernel32")]

private static extern int getprivateprofilestring(string section, string key,

string def, stringbuilder retval, int size, string filepath); 

當然還要引用

using system.text;

using system.runtime.interopservices;

INI檔案程式設計

在我們寫的程式當中,總有一些配置資訊需要儲存下來,以便完成程式的功能,最簡單的辦法就是將這些資訊寫入ini檔案中,程式初始化時再讀入.具體應用如下 一.將資訊寫入.ini檔案中.1.所用的winapi函式原型為 bool writeprivateprofilestring lpctstr lpkey...

Delphi中的INI檔案程式設計

tinifile類中定義了許多成員函式,這裡介紹幾個使用頻率較高的成員函式 create 函式定義為 constructor create const filename string 該函式建立tinifile類的物件。引數filename是要讀寫的初始化檔名。若讀寫的檔案在windows的目錄裡 ...

Delphi中的INI檔案程式設計

delphi 中的ini 檔案程式設計 ini 檔案在系統配置及應用程式引數儲存與設定方面,具有很重要的作用,所以視覺化的程式設計一族,如vb vc vfp delphi 等都提供了讀寫 ini檔案的方法,其中 delphi 中操作ini 檔案,最為簡潔,這是因為 delphi3 提供了乙個 tin...