VC操作INI文件(二)

2014-02-08 13:35:52 · 作者: · 浏览: 346

 

  CIniFile类

  以下提供对Windows操作INI文件的API的简单封装类CIniFile.

  [cpp] view plaincopyprint

  // IniFile.h

  #ifndef __INIFILE_H__

  #define __INIFILE_H__

  class CIniFile

  {

  public:

  CIniFile();

  CIniFile(LPCTSTR szFileName);

  virtual ~CIniFile();

  public:

  // Attributes

  void SetFileName(LPCTSTR szFileName);

  public:

  // Operations

  BOOL SetProfileInt(LPCTSTR lpszSectionName, LPCTSTR lpszKeyName, int nKeyValue);

  BOOL SetProfileString(LPCTSTR lpszSectionName, LPCTSTR lpszKeyName, LPCTSTR lpszKeyValue);

  DWORD GetProfileSectionNames(CStringArray& strArray); // 返回section数量

  int GetProfileInt(LPCTSTR lpszSectionName, LPCTSTR lpszKeyName);

  DWORD GetProfileString(LPCTSTR lpszSectionName, LPCTSTR lpszKeyName, CString& szKeyValue);

  BOOL DeleteSection(LPCTSTR lpszSectionName);

  BOOL DeleteKey(LPCTSTR lpszSectionName, LPCTSTR lpszKeyName);

  private:

  CString  m_szFileName; // .//Config.ini, 如果该文件不存在,则exe第一次试图Write时将创建该文件

  UINT m_unMaxSection; // 最多支持的section数(256)

  UINT m_unSectionNameMaxSize; // section名称长度,这里设为32(Null-terminated)

  void Init();

  };

  #endif

  // IniFile.cpp

  #include "IniFile.h"

  void CIniFile::Init()

  {

  m_unMaxSection = 512;

  m_unSectionNameMaxSize = 33; // 32位UID串

  }

  CIniFile::CIniFile()

  {

  Init();

  }

  CIniFile::CIniFile(LPCTSTR szFileName)

  {

  // (1) 绝对路径,需检验路径是否存在

  // (2) 以"./"开头,则需检验后续路径是否存在

  // (3) 以"/"开头,则涉及相对路径的解析

  Init();

  // 相对路径

  m_szFileName.Format(".//%s", szFileName);

  }

  CIniFile::~CIniFile()

  {

  }

  void CIniFile::SetFileName(LPCTSTR szFileName)

  {

  m_szFileName.Format(".//%s", szFileName);

  }

  DWORD CIniFile::GetProfileSectionNames(CStringArray &strArray)

  {

  int nAllSectionNamesMaxSize = m_unMaxSection*m_unSectionNameMaxSize+1;

  char *pszSectionNames = new char[nAllSectionNamesMaxSize];

  DWORD dwCopied = 0;

  dwCopied = ::GetPrivateProfileSectionNames(pszSectionNames, nAllSectionNamesMaxSize, m_szFileName);

  strArray.RemoveAll();

  char *pSection = pszSectionNames;

  do

  {

  CString szSection(pSection);

  if (szSection.GetLength() < 1)

  {

  delete[] pszSectionNames;

  return dwCopied;

  }

  strArray.Add(szSection);

  pSection = pSection + szSection.GetLength() + 1; // next section name

  } while (pSection && pSection<PSZSECTIONNAMES+NALLSECTIONNAMESMAXSIZE); pre