您的位置:首页 > 其它

INI文件的读取

2014-03-15 00:24 211 查看

6.2.3 INI文件的读取

INI文件是Windows系统最早采用的文本文件格式,比如:在C:驱动器根目录中往往都会存在着一个隐藏的boot.ini文件,它用来定义计算机启动时显示的系统菜单。笔者的boot.ini文件如下所示:

[boot loader]  
timeout=30  
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS  
[operating systems]  
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP   
Professional" /noexecute=optin /fastdetect

可以看出,INI文件格式有点类似于properties文件,但是它多出一个Section(节)的概念。一个INI 文件可以分为几个 Section,每个 Section 的名称用"[]"括起来,在一个 Section中,就包含有key=value组成的多条属性值。如上所示的boot.ini中,它就包含两个Section,一个是[boot loader],另外一个是[operating systems]。

Windows 对INI文件操作的 API中,有一部分是对 win.ini 操作的,另一部分是对用户自定义的INI文件操作的,这种分类如表6-11所示。

表6-11
文本操作CRT函数
函数
含义
GetProfileInt
从win.ini文件指定Section中读取一个int属性值
GetProfileSection
从win.ini文件指定Section中获取所有的属性
GetProfileString
从win.ini文件指定Section中读取一个文本属性值
WriteProfileSection
向win.ini文件写入一个Section
WriteProfileString
向win.ini文件指定Section中写入一个文本属性值
GetPrivateProfileInt
从指定的INI文件的Section中读取一个int属性值
GetPrivateProfileSection
从指定的INI文件中读取指定的Section
GetPrivateProfileSectionNames
从指定的INI文件中获取所有的Section名
GetPrivateProfileString
从指定的INI文件的Section中读取一个文本属性值
GetPrivateProfileStruct
从指定的INI文件的Section中读取一个结构属性值
WritePrivateProfileSection
向指定的INI文件写入一个Section
WritePrivateProfileString
向指定的INI文件的Section中写入一个文本属性值
WritePrivateProfileStruct
向指定的INI文件的Section中写入一个结构属性值
可以看到,这些函数主要包括两类:包含private的用户INI文件操作和不包含private的Win.ini文件操作。自从有了Windows注册表,我们很少再依赖于Win.ini文件来读取和写入配置信息,因此我们常常使用PrivateXXX函数族来操作指定的ini文件。

现在动手

接下来,我们使用Win32 API读出boot.ini文件的内容。

【程序 6-3】使用Windows API读取INI文件

01  #include "stdafx.h" 
02    
03  int _tmain()  
04  {  
05      TCHAR buffer[256];  
06      TCHAR path[] = _T("c:\\boot.ini");  
07      int len = GetPrivateProfileSectionNames
(buffer, sizeof(buffer), path);  
08    
09      TCHAR *names = buffer;  
10      TCHAR *end = names + len;  
11    
12      //返回的sectionNames以null分隔  
13    
14      while(names < end)  
15      {  
16          CString name = names;  
17          _tprintf(_T("======%s======\r\n"), name);  
18          names += name.GetLength();  
19          names ++;  
20    
21          //获取该Section下面所有的属性  
22          TCHAR buffer2[1024];  
23          len = GetPrivateProfileSection(name, 
buffer2, sizeof(buffer2), path);  
24          //遍历所有行  
25          TCHAR *lines = buffer2;  
26          while(*lines)  
27          {  
28              CString line = lines;   
29              _tprintf(_T("\t%s\r\n"), line);  
30    
31              lines += line.GetLength();  
32              lines ++;  
33          }  
34      }  
35    
36      return 0;37 }

运行结果如图6-11所示。



(点击查看大图)图6-11 运行结果
光盘导读

该项目对应于光盘中的目录"\ch06\BootIniReader"。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: