-1

is

find

function can't work with exe? i try to find wstring in an exe. it always not match. but if i create a txt and copy binary inside exe to txt and it can find it.

    std::wifstream file(L"D:/file.exe", std::ios::binary);
if (file.is_open())
{
    file.seekg(0, file.end);
    std::streamoff length = file.tellg();
    file.seekg(0, file.beg);
    wchar_t *buffer = new wchar_t[length];
    file.read(buffer, length);
    std::wstring sFile;
    sFile = buffer;
    size_t index = sFile.find(L"Something");
    if (index != std::string::npos) std::cout << "It's found";
    file.close();
    delete[] buffer;
}
else
{
    std::cout << "It's not open";
}
  • 2
    The problem is that `std::wifstream` does not read Unicode (UTF-16) by default. It sees a byte stream and tries to convert it to UTF-16 using the current locale. If you want to read the file "as is", use `std::fstream` instead and search for the bytes that compose the UTF-16 sub string. – zett42 Nov 15 '18 at 14:01
  • @zett42 i need to work with unicode file path. there's a value i pass to wifstream. thats why i stick to wifstream. – Dwerson busch Nov 15 '18 at 14:24
  • `std::ifstream` constructor has an overload for `const wchar_t*` path on the Windows platform, so you can use it aswell. From your acceptance of [this answer](https://stackoverflow.com/a/53320804/7571258) I infer that you don't really want to search for UTF-16, but rather ANSI or ASCII string. Otherwise this answer wouldn't work for you. So you should use `std::ifstream` in the first place to avoid needless ANSI to Unicode conversion. – zett42 Nov 15 '18 at 14:31
  • This code is all kinds of wrong. There are [MUCH better ways to read a file into a string](https://stackoverflow.com/questions/116038/). – Remy Lebeau Nov 15 '18 at 17:49

2 Answers2

3

The executable probably has a number of 0 bytes (i.e. 0x00) early on in the file. When you do sFile = buffer; it assumes that buffer is a C-style string that ends in a 0 byte. So sFile will only contain the bytes up to that point.

To fix it you should put the whole buffer into the string:

std::wstring sFile(buffer, length); // Directly using the constructor, or
sFile.assign(buffer, length);       // after construction
Kevin
  • 5,297
  • 1
  • 12
  • 20
1

Just change

std::wstring sFile;
sFile = buffer;

to

std::wstring sFile(buffer, buffer+length);

When you assigning char-buffer to wstring object, the length of the string is determined by the first null character. So, the first 0x00 byte containing in your file denotes the end of string.

snake_style
  • 1,120
  • 7
  • 15