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);
我有这个小程序从FTP服务器读取文本文件到字符串,但在读取字符串的末尾有一些额外的字符。我想问题是文字的大小,但我无法弄明白。
例如,我想下载一个加密的文本,它会像这样被破坏
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
8最后不应该在那里。
答案 0 :(得分:4)
函数InternetReadFile不会使null终止缓冲区,因此数组tmp的内容不是字符串,而是将其视为字符串。
行为未定义。
删除此行:
buffer += (string)tmp;
而是使用字符串函数append的重载,它接受一个数组及其大小:
buffer.append( tmp , rSize );
答案 1 :(得分:2)
2501表示你没有考虑到NULL终止符,所以你想做的就是这样的
DWORD rSize;
char tmp[2048+1];
string buffer;
while(InternetReadFile(hFile, tmp, 2048, &rSize) && rSize > 0)
{
tmp[rSize] = '\0';
buffer += (string)tmp;
}