c - Win32 API - Trying to readfile, it's getting truncated -- why? -
i trying read file , display file in ascii or hex hedit. running other computations on file info right want see all.
currently code displays first bit - "mz" - thats it. somehow accidentally truncating pszfiletext variable, want able view entire executable in window.
bool readinexefile(hwnd hedit, lpctstr pszfilename) { handle hfile; bool bsuccess = false; 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) { lpstr pszfiletext; pszfiletext = globalalloc(gptr, dwfilesize + 1); if(pszfiletext != null) { dword dwread; if(readfile(hfile, pszfiletext, dwfilesize, &dwread, null)) { pszfiletext[dwfilesize] = 0; // add null terminator if(setwindowtext(hedit, pszfiletext)) { bsuccess = true; // worked! } } globalfree(pszfiletext); } } closehandle(hfile); } return bsuccess;
}
exe files binary, you trying display raw binary data as-is, not work. on right track thinking need encode binary data hex before displaying it. binary data not displayable, hex is.
try instead:
static const tchar hex[] = text("0123456789abcdef"); bool readinexefile(hwnd hedit, lpctstr pszfilename) { bool bsuccess = false; handle hfile = createfile(pszfilename, generic_read, file_share_read, null, open_existing, 0, null); if (hfile != invalid_handle_value) { dword dwfilesize = getfilesize(hfile, null); if (dwfilesize != invalid_file_size) { lptstr pszfiletext = (lptstr) localalloc(lmem_fixed, ((dwfilesize * 3) + 1) * sizeof(tchar)); if (pszfiletext != null) { byte buffer[1024]; dword dwoffset = 0; dword dwread; (dword dwfilepos = 0; dwfilepos < dwfilesize; dwfilepos += dwread) { if (!readfile(hfile, buffer, sizeof(buffer), &dwread, null)) { closehandle(hfile); return false; } if (dwread == 0) break; (dword idx = 0; idx < dwread; ++idx) { pszfiletext[dwoffset++] = hex[(buffer[idx] & 0xf0) >> 4]; pszfiletext[dwoffset++] = hex[buffer[idx] & 0x0f]; pszfiletext[dwoffset++] = text(' '); } } pszfiletext[dwoffset] = 0; // add null terminator bsuccess = setwindowtext(hedit, pszfiletext); localfree(pszfiletext); } } closehandle(hfile); } return bsuccess; }
Comments
Post a Comment