zoukankan      html  css  js  c++  java
  • C++读写ini配置文件

    配置文件中经常用到ini文件,在VC中其函数分别为:

    写入.ini文件:

    BOOL WritePrivateProfileString(
      LPCTSTR lpAppName,  // INI文件中的一个字段名[节名]可以有很多个节名
    
      LPCTSTR lpKeyName,  // lpAppName 下的一个键名,也就是里面具体的变量名
    
      LPCTSTR lpString,   // 键值,也就是数据
    
      LPCTSTR lpFileName  // INI文件的路径
    );
    

    读取.ini文件:

    DWORD GetPrivateProfileString(
      LPCTSTR lpAppName,        // INI文件中的一个字段名[节名]可以有很多个节名
    
      LPCTSTR lpKeyName,        // lpAppName 下的一个键名,也就是里面具体的变量名
    
      LPCTSTR lpDefault,        // 如果lpReturnedString为空,则把个变量赋给lpReturnedString
    
      LPTSTR lpReturnedString,  // 存放键值的指针变量,用于接收INI文件中键值(数据)的接收缓冲区
    
      DWORD nSize,            // lpReturnedString的缓冲区大小
    
      LPCTSTR lpFileName        // INI文件的路径
    );
    

    读取整形值:(返回值为读到的整)

    UINT GetPrivateProfileInt(
      LPCTSTR lpAppName,  // INI文件中的一个字段名[节名]可以有很多个节名
      LPCTSTR lpKeyName,  // lpAppName 下的一个键名,也就是里面具体的变量名
      INT nDefault,       // 如果没有找到指定的数据返回,则把个变量值赋给返回值
    
      LPCTSTR lpFileName  // INI文件的路径
    
    );
    

    读写INI文件时相对路径和绝对路径都可以,根据实际情况选择

    "..//IniFileName.ini"    // 这样的为相对路径
    
    "D://IniFileName.ini"    // 这样的为绝对路径
    

    MAX_PATH:是微软最大路径占的字节所设的宏

    例子:

    写INI文件:

    LPTSTR lpPath = new char[MAX_PATH];
    
    strcpy(lpPath, "D://IniFileName.ini");
    
    WritePrivateProfileString("LiMing", "Sex", "Man", lpPath);
    WritePrivateProfileString("LiMing", "Age", "20", lpPath);
    
    WritePrivateProfileString("Fangfang", "Sex", "Woman", lpPath);
    WritePrivateProfileString("Fangfang", "Age", "21", lpPath);
    
    delete [] lpPath;
    

    INI文件如下:

    [LiMing]
    Sex=Man
    Age=20
    [Fangfang]
    Sex=Woman
    Age=21

    读INI文件:

    LPTSTR lpPath = new char[MAX_PATH];
    LPTSTR LiMingSex = new char[6];
    int LiMingAge;
    LPTSTR FangfangSex = new char[6];
    int FangfangAge;
    
    strcpy(lpPath, "..//IniFileName.ini");
    
    GetPrivateProfileString("LiMing", "Sex", "", LiMingSex, 6, lpPath);
    LiMingAge = GetPrivateProfileInt("LiMing", "Age", 0, lpPath);
    
    GetPrivateProfileString("Fangfang", "Sex", "", FangfangSex, 6, lpPath);
    FangfangAge = GetPrivateProfileInt("Fangfang", "Age", 0, lpPath);
    
    delete [] lpPath;
    
  • 相关阅读:
    第20月第30日 集体智慧编程
    第20月第29天 cocoa抽象工厂 cocoapods组件化 cocoapods升级
    第20月第28天 tensorflow
    第20月第27天 游戏编程的人工智能
    第20月第22天 2016计算机大会后记——机器学习:发展与未来
    第20月第18天 小码哥swift
    第20月第17天 mvvm 多次点击push -ObjC
    第20月第14天 objc_getAssociatedObject _cmd
    第20月第9天 paddlepaddle
    第20月第4天 pycharm utf-8
  • 原文地址:https://www.cnblogs.com/lixuejian/p/13086915.html
Copyright © 2011-2022 走看看