用Visual C 操作INI檔案

2021-04-06 12:01:44 字數 2741 閱讀 3869

配置檔案字串和 .ini 檔案

windows 3.x 應用程式能夠直接訪問 .ini 檔案。然而,這些**在 32 位 windows 作業系統中不能使用,因為 .ini 檔案中的資訊被註冊資料庫替換。該資料庫具有一些優點,包括防止應用程式損壞系統資訊的安全控制、錯誤記錄、遠端軟體更新和遠端管理工作站軟體。

可 以利用 windows 3.x 和所有 32 位 windows 作業系統支援的配置檔案 api 編寫可移植的**。呼叫 getprofilestring 和 writeprofilestring api 函式,而不是直接訪問 .ini 檔案。這些函式使用編譯環境支援的任何乙個基礎機制(.ini 檔案或者註冊資料庫)。

用visual c++操作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,strtemp;

int nage;

strname="張三";

nage=12;

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

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

[studentinfo]

name=張三

3.要將學生的年齡儲存下來,只需將整型的值變為字元型即可:

strtemp.format("%d",nage);

::writeprivateprofilestring("studentinfo","age",strtemp,"c://stud//student.ini");

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

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

dword getprivateprofilestring(

lpctstr lpkeyname,

lpctstr lpdefault,

lptstr lpreturnedstring,

dword nsize,

lpctstr lpfilename

); 其中各引數的意義:

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

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

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

nsize : 目的快取器的大小.

lpfilename : 是完整的ini檔名.

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

cstring strstudname;

int nstudage;

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

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

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

uint getprivateprofileint(

lpctstr lpkeyname,

int ndefault,

lpctstr lpfilename

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

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

三.迴圈寫入多個值,設現有一程式,要將最近使用的幾個檔名儲存下來,具體程式如下:

1.寫入:

cstring strtemp,strtempa;

int i;

int ncount=6;

file://共有6個檔名需要儲存

for(i=0;i

strtemp.format("%d",ncount);

::writeprivateprofilestring("filecount","count",strtemp,"c://usefile//usefile.ini");

file://將檔案總數寫入,以便讀出.

2.讀出:

ncount=::getprivateprofileint("filecount","count",0,"c://usefile//usefile.ini");

for(i=0;i

補充幾點:

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

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

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

用Visual C 操作INI檔案

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

用Visual C 操作INI檔案

在我們寫的程式當中,總有一些配置資訊需要儲存下來,以便完成程式的功能,最簡單的辦法就是將這些資訊寫入ini檔案中,程式初始化時再讀入.具體應用如下 一.將資訊寫入.ini檔案中.1.所用的winapi函式原型為 2.具體使用方法 設現有一名學生,需把他的姓名和年齡寫入 c stud student....

用VC操作INI檔案

原文http www.cnblogs.com boneking archive 2008 11 04 1326221.html 三.迴圈寫入多個值,設現有一程式,要將最近使用的幾個檔名儲存下來,具體程式如下 1.寫入 cstring strtemp,strtempa int i int ncount...