C ++ FTP写入文件不起作用

时间:2013-12-04 00:24:46

标签: c++ file upload ftp

我编写了 SUPPOSED 代码来写入ftp服务器上的文件,但它不起作用。该文件保持0个字节。也没有错误。这是我的代码:

#include <windows.h>
#include <wininet.h>
#include <stdio.h>

int main()
{
    int error=0;
    char buffer[256];
    char *text="Hello world.";
    HINTERNET hOpen=InternetOpen("",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,INTERNET_FLAG_PASSIVE);
    InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
    printf("hOpen:%d:%s\n",error,buffer);
    HINTERNET hConnect=InternetConnect(hOpen,"diabloip.host22.com",INTERNET_DEFAULT_FTP_PORT,"MY_USER_NAME","MY_PASSWORD",INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
    InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
    printf("hConnect:%d:%s\n",error,buffer);
    HINTERNET hFile=FtpOpenFile(hConnect,"diabloip.host22.com/public_html/log.txt",GENERIC_WRITE,FTP_TRANSFER_TYPE_ASCII,0);
    InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
    printf("hFile:%d:%s\n",error,buffer);
    InternetWriteFile(hFile,text,strlen(text),NULL);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

问题是将NULL作为InternetWriteFile的最后一个参数传递。它不是一个可选参数,如果您对该通话进行了错误检查,则会看到GetLastError返回87或ERROR_INVALID_PARAMETER

这可以正常工作,并清除一些其他问题,包括错误的参数和过多的掩盖问题。

#include <windows.h>
#include <wininet.h>
#include <stdio.h>

#pragma comment(lib, "wininet.lib")

void PrintStatus(const char* title)
{
    DWORD error = 0;
    DWORD sz = 256;
    char buffer[256];
    InternetGetLastResponseInfo(&error, buffer, &sz);
    printf("%s:%u:%s\n", title, error, buffer);
}

int main()
{
    const char *text = "Hello world.";
    HINTERNET hOpen = InternetOpen("", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_PASSIVE);
    PrintStatus("hOpen");
    HINTERNET hConnect = InternetConnect(hOpen, "localhost", INTERNET_DEFAULT_FTP_PORT, "test", "test", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
    PrintStatus("hConnect");
    HINTERNET hFile = FtpOpenFile(hConnect, "log.txt", GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0);
    PrintStatus("hFile");
    DWORD wb = 0;
    BOOL Success = InternetWriteFile(hFile, text, strlen(text), &wb);
    if(!Success)
    {
        DWORD err = GetLastError();
        printf("InternetWriteFile - Error = %u\n", err);
    }
    PrintStatus("InternetWriteFile");
    InternetCloseHandle(hOpen);
    return 0;
}