Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Win32, how can a text file be successfully read into memory?
    primarykey
    data
    text
    <p>I am trying to get simple file IO working in Win32. So far the writing is working fine, but the reading is not: although it successfully reads the contents, additional "garbage" is appended to the string. The code I have so far is below. The program has <code>UNICODE</code> defined.</p> <p>For writing:</p> <pre><code>DWORD dwTextSize = GetWindowTextLength(hWndTextBox); WCHAR *lpszText = new WCHAR[dwTextSize]; GetWindowText(hWndTextBox, lpszText, dwTextSize + 1); hTextFile = CreateFile(lpszTextFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); DWORD dwBytesWritten; WriteFile(hTextFile, lpszText, 2 * dwTextSize, &amp;dwBytesWritten, NULL); // x2 for 2 bytes per Unicode character CloseHandle(hTextFile); DeleteObject(hTextFile); </code></pre> <p>For this example, <code>Hello, World!</code> is saved successfully as <code>Hello, World!</code>.</p> <p>For reading:</p> <pre><code>lpszTextFileName = L"text.txt"; // LPCTSTR Variable hTextFile = CreateFile(lpszTextFileName, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); DWORD dwFileSize = GetFileSize(hTextFile, &amp;dwFileSize); DWORD dwBytesRead; WCHAR *lpszText = new WCHAR[dwFileSize / 2]; ReadFile(hTextFile, lpszText, dwFileSize, &amp;dwBytesRead, NULL); CloseHandle(hTextFile); </code></pre> <p>The string is then used to set the text of an EDIT control:</p> <pre><code>SendMessage(hWndTextBox, WM_SETTEXT, NULL, (LPARAM)lpszText); // SetWindowText() also possible </code></pre> <p>When <code>Hello, World!</code> is read back in, it reads back in as <code>Hello, World!﷽﷽ꮫꮫꮫꮫﻮ</code> or a visual variation upon this, but basically "garbage"!</p> <p>I have probably missed something rather obvious, but I cannot see where! Is there a solution to this problem and if so, what is it?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload