I have a small problem. I am trying to save some text from a Win32 Edit Control using fstream. My code:
LPTSTR text = L"";
ofstream file;
GetDlgTextItem(hWnd, EDIT_MAIN, text, UINT_MAX);
file.open(filePathName);
file << text;
file.close()
If I type in hello world and save it, the text file shows something else, such as 001D2F38. Any solutions?
You need to allocate memory to receive the text, and you need to make sure the data type of the text buffer matches the data type you use for writing to the file. Neither of which you are doing.
Try something more like this:
HWND hEdit = GetDlgItem(hWnd, EDIT_MAIN);
int len = GetWindowTextLengthA(hEdit);
std::vector<CHAR> text(len+1, 0);
GetWindowTextA(hEdit, &text[0], len);
ofstream file;
file.open(filePathName);
file << &text[0];
file.close();
Or:
HWND hEdit = GetDlgItem(hWnd, EDIT_MAIN);
int len = GetWindowTextLengthW(hEdit);
std::vector<WCHAR> text(len+1, 0);
GetWindowTextW(hEdit, &text[0], len);
wofstream file;
file.open(filePathName);
file << &text[0];
file.close();
Or even something more like this:
HWND hEdit = GetDlgItem(hWnd, EDIT_MAIN);
int len = GetWindowTextLengthW(hEdit);
std::vector<WCHAR> text(len+1, 0);
GetWindowTextW(hEdit, &text[0], len);
int len2 = WideCharToMultiByte(CP_UTF8, 0, &text[0], len, NULL, 0, NULL, NULL);
std::vector<char> utf8(len2+1, 0);
WideCharToMultiByte(CP_UTF8, 0, &text[0], len, &utf8[0], len2, NULL, NULL);
ofstream file;
file.open(filePathName);
file << &utf8[0];
file.close();