C++

[C/C++] ini file read/write

jeylee 2024. 3. 7. 13:14


 

C++ 언어로 .ini 파일을 쓰고 읽는 코드를 알아 봅시다.

 

// Main.cpp

#include <iostream>
#include <string>

#include <Windows.h>
#include <io.h>

#include <codecvt> // for wstring_convert
#include <locale>  // for codecvt_utf8

using namespace std;

int main()
{
	wstring wpath = L"./Sample.ini";

	// ini file write -----

	wchar_t value[256];
	wsprintfW(value, L"this is Value %d", 1); // make value
	WritePrivateProfileString(L"Section", L"Name", value, wpath.c_str());

	// ini file read -----

	wstring_convert<codecvt_utf8<wchar_t>> converter;
	string spath = converter.to_bytes(wpath);
	if (_access(spath.c_str(), 0) != -1) // file check
	{
		LPWSTR cBuf;
		cBuf = (LPWSTR)malloc(sizeof(LPWSTR) * 256);

		GetPrivateProfileString(L"Section", L"Name", nullptr, cBuf, 256, wpath.c_str());

		if (cBuf)
		{
			wstring temp(cBuf);
			wcout << temp << endl;
		}

		free(cBuf);
	}

	return 0;
}

 

위 코드를 실행하면 실행 위치에 Simple.ini 파일이 생성되고 내부의 Section의 Name 데이터를 가져와 출력하는 코드입니다.