现在的位置: 首页 > 综合 > 正文

INI文件的读取

2014年09月25日 ⁄ 综合 ⁄ 共 2452字 ⁄ 字号 评论关闭


6.2.3  INI文件的读取

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

  1. [boot loader]  
  2. timeout=30  
  3. default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS  
  4. [operating systems]  
  5. multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP   
  6. 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文件

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

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

 
(点击查看大图)图6-11  运行结果

光盘导读

该项目对应于光盘中的目录"\ch06\BootIniReader"。

抱歉!评论已关闭.