I am writing a simple text editor using the Win32 API and I am trying to write a function to compare the content of the file to the content of an edit control. I currently have this:
BOOL checkForModification (PCWSTR pszFileName, HWND hEdit) {
BOOL bSuccess = FALSE;
DWORD dwTextLength = GetWindowTextLengthA(hEdit);
hFile = CreateFile(pszFileName, GENERIC_READ,
FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwFileSize;
dwFileSize = GetFileSize(hFile, NULL);
if (dwFileSize != 0xFFFFFFFF)
{
PSTR pszFileText;
pszFileText = (PSTR)GlobalAlloc(GPTR, dwFileSize + 1);
if (pszFileText != NULL) {
DWORD dwRead;
if (ReadFile(hFile, pszFileText, dwFileSize + 1, &dwRead, NULL))
{
bSuccess = TRUE;
pszFileText[dwFileSize] = 0;
LPSTR pszEditText = (LPSTR)GlobalAlloc(GPTR, dwTextLength + 1);
GetWindowTextA(hEdit, pszEditText, dwTextLength);
int res = CompareStringA(LOCALE_SYSTEM_DEFAULT, NULL, pszFileText, -1, pszEditText, -1);
if (res != CSTR_EQUAL) {
MessageBox(NULL, L"You changed the text!", L"Alert", MB_OK | MB_ICONINFORMATION);
}
GlobalFree(pszEditText);
}
else {
MessageBox(NULL, L"Oh no! Something went wrong!\nError code: 2", L"Error", MB_OK | MB_ICONERROR);
}
GlobalFree(pszFileText);
}
}
CloseHandle(hFile);
}
else {
MessageBox(NULL, L"Oh no! Something went wrong!\nError code: 1", L"Error", MB_OK | MB_ICONERROR);
}
return bSuccess;
}
The problem that I am having is that the result of CompareStringA
is always returning CSTR_LESS_THAN
, even when I don't change the text in the edit control. The encoding of the file is UTF-8. Why is this happening?
Seriously, use a debugger and test it with a file that contains simple text like ABCDE. You should be able to figure out the problem in less than 30 seconds just by inspecting a few variables!
You can trivially determine that the problem is not reading the documentation of function GetWindowTextA
(https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowtexta).
The size you pass include the null terminating charaters. Assuming that the edit also contains ABCDE, then the length is 5.
Calling GetWindowTextA(hEdit, pszEditText, dwTextLength);
where dwTextLength
will returns a buffer that contains ABCD plus the null character.
Obviously ABCD is before ABCDE using usual sorting rules.