Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Visual C++: Read and Write INI Files

📅 2010-Jan-31 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, ini files ⬩ 📚 Archive

I find it useful to keep the settings for my application separated from the code in a initialization (INI) file. The application code reads these settings at runtime and uses them for initialization of its objects. This separation means that I can try the application with different settings without having to recompile the code. (C++ code takes ages to compile!) And the INI file is human readable and writable easily using any text editor.

A simple INI file:

; Foobar Settings (foobar.ini)

; Database settings
USER_NUM_MAX = 256  ; Maximum number of users

; Operation settings
CRITICAL_SIZE = 100000  ; Maximum memory

The Initialization (INI) file format is simple. Anything to the right of a semicolon ; is a comment. Sections are named within a pair of square brackets []. Key-value pairs are written as key=value.

To read an integer or string value use [GetPrivateProfileInt()]( or [GetPrivateProfileString()]( To write a string value back to a key use [WritePrivateProfileString()]( (There is no function to write back an integer, convert it to a string.)

#include <Windows.h>

int userNumMax = GetPrivateProfileInt("DB_SETTINGS", "USER_NUM_MAX", 0, "foobar.ini");
WritePrivateProfileString("DB_SETTINGS", "USER_NUM_MAX", "99", "foobar.ini");

For other functions related to INI files look for those with the prefix GetPrivateProfile and WritePrivateProfile in Registry Functions. The functions with prefix GetProfile are meant for [win.ini](, which should be not be useful to anyone!

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧