Load a text file with C++

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
std::wstring fromAscii(const char* str)
{
	std::wstring sOutput;
	int inputLength = (int)strlen(str);
	if(inputLength)
	{
		inputLength++; // allow for null terminator
		wchar_t* buf = new wchar_t[inputLength];
		MultiByteToWideChar(CP_ACP, 0, str, inputLength, buf, inputLength);
		sOutput += buf;
		delete[] buf;
	}
	return sOutput;
}
bool LoadTextFile(std::wstring const& path, std::wstring& text)
{
    try
    {
        std::ifstream ifs(path);
        std::string str((std::istreambuf_iterator(ifs)), std::istreambuf_iterator());
        text = fromAscii(str.c_str());
        return true;
   }
   catch(...)
   {
   }
    return false;
}