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

标签 c++ file upload ftp

我编写的这段代码应该 写入 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;
}

最佳答案

问题是将 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;
}

关于C++ FTP 写入文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364482/

相关文章:

c++ - CMake添加到Clang的包含路径

python - 值错误: need more than 0 values to unpack

c++ - 如何在不关闭 C++ fstream 文件的情况下保存和读取它

c++ - 在特定的 Unicode 路径中创建文件

python - 使用 Python 和 Alfresco API 上传文件

c++ - 派生类的方法需要向下转换其参数

c++ - 使用多线程的硬盘争用

java - 如何在 Servlet 请求中将传入字节直接写入磁盘?

c++ - 如何使用 C++ 将 .csv 文件上传到 SQL Server

c++ - 使用复制构造函数的程序输出错误