Paralyz3d
Paralyz3d

Reputation: 333

InternetReadFile returns text with extra characters at the end

HINTERNET hInternet, hFtpSession, hFile;

    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    hFtpSession = InternetConnect(hInternet, FTPHOST, INTERNET_DEFAULT_FTP_PORT,
        FTPUSER, FTPPASS, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    hFile = FtpOpenFile(hFtpSession, argv[1], GENERIC_READ, FTP_TRANSFER_TYPE_ASCII, 0);

    DWORD rSize;
    char tmp[2048];
    string buffer;

    while(InternetReadFile(hFile, tmp, 2048, &rSize) && rSize > 0)
    {
        buffer += (string)tmp;
    }

    cout << buffer;

    InternetCloseHandle(hFile);
    InternetCloseHandle(hFtpSession);
    InternetCloseHandle(hInternet);

I have this small program to read a text file from an FTP server to a string, but in the end of the read string there are some extra characters. I guess the problem is with the size of the text but I can't figure it out.

For example I want to download an encrypted text it will be corrupted like this

MIICIDANBgkqhkiG9w0BAQEFAAOCAg0AMIICCAKCAgEAp2q+92EQPncY0sN6SMTC0yh05GpZ
FUEGATvUx/zcUrzdDTva5JKz0MztuCn3lnHmaUB6L97w8fuVOhJjj90ItH4FdUk4R9m50son
DSZ4ad5ZKi7WE7GApIq21vgM0zoG5sr0Xb6X41IQgvYF7i9nX4zKO2znRyD3uzBqkqkhWzbS
HI2euCdhmXfx2az0ynNKrcnQINaWowipc0LrW0Q9PWI1McCs4V5sz8GkBMpKENb3m/LBlSqz
TboC/9hiD9Yfclvk3wFeNGvsnUUDpwZipF9cBMVzmfyjA1gBDNLV8qcTXSortHaGeHdLpqIg
Qn3SpDol8gPRis7A7Hy4KjRS8Y/iZa8Nv9EmEeful6u3IHY0Qror/wOeST5WhaTynVBT0wgP
6GSMWsofwA3NttsFCw55z5c8GBEGP6Uo+jP/rdiYvednT0iV8Grp+XJ6zMFqYlVcLqAzQWLw
dfqve/lr8+OKfR9WvG6hvrVduTnoy+LBFF/QEVxAlZqymlXMm/hcO/TUoE1Kmon6FwID4Mek
nV1eb1aCmUIzxFHtPkMO0KFitmxa5EGwAFHRAjXrp2lUHIQSaWwVnsfoQgmrG9ux2I27w+WR
8kFdkqWrutFz2xn6ovVwla7Oj0iL2f9azNO2Z2KT/sBPwGmI67M9Ceih0YLD0w7Woy32H2aM
mIeK368CARE=
8

The 8 shouldn't be there at the end.

Upvotes: 1

Views: 1128

Answers (2)

BnBDim
BnBDim

Reputation: 136

As 2501 said you aren't taking into account the NULL terminator, so what you would want to do would be something like this

DWORD rSize;
char tmp[2048+1];
string buffer;

while(InternetReadFile(hFile, tmp, 2048, &rSize) && rSize > 0)
{
    tmp[rSize] = '\0';
    buffer += (string)tmp;
}

Upvotes: 2

2501
2501

Reputation: 25752

The function InternetReadFile doesn't null terminate the buffer, so the content of the array tmp is not a string, yet you treat it as such.

The behavior is undefined.

Remove this line:

buffer += (string)tmp;

Instead use the overload of the string function append, which takes an array and it's size:

buffer.append( tmp , rSize );

Upvotes: 4

Related Questions