在wininet ftp程序

时间:2015-12-16 15:45:59

标签: c++ windows ftp wininet

所以我找到了这个c ++程序,我想我会用它来自动备份我的文件到我的桌面ftp服务器,但它总是遇到相同的seg故障问题,检查ftp服务器日志后我可以看到它是实际连接到ftp服务器并使用用户名和密码登录,但当它到达实际的上传部分时它会崩溃。

我在dev c ++中通过调试器运行它,它说"访问冲突(Seg faut)"

这是wininet的错误吗?如果是这样,还有某种解决方法吗?

#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet")
#include <fstream>
#include <string.h>

int send(const char * ftp, const char * user, const char * pass, const char * pathondisk, char * nameonftp)
{

HINTERNET hInternet;
HINTERNET hFtpSession;
hInternet = InternetOpen(NULL,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
if(hInternet==NULL)
{
    cout << GetLastError();
    //system("PAUSE");
    return 1;
}
hFtpSession = InternetConnect(hInternet,
(LPTSTR)ftp, INTERNET_DEFAULT_FTP_PORT,
(LPTSTR)user, (LPTSTR)pass, INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE, 0);
if(hFtpSession==NULL)
{
    cout << GetLastError();
    //system("PAUSE");
    return 1;
}
Sleep(1000);
char * buf=nameonftp;
strcat(buf,".txt");
if (!FtpPutFile(hFtpSession, (LPTSTR)pathondisk, (LPTSTR)buf, FTP_TRANSFER_TYPE_ASCII, 0)) {
    cout << GetLastError();//this is never reached
    return 1;
}
Sleep(1000);
InternetCloseHandle(hFtpSession);
InternetCloseHandle(hInternet);
return 0;
}

int main() {
send("127.0.0.1","testuser","test","file.pdf","backup");
return 0;
}

1 个答案:

答案 0 :(得分:0)

您不得修改字符串文字。将字符串复制到新缓冲区以编辑内容。

此外,您应该使用hogeA() API让系统明确使用ANSI字符集。

试试这个:

#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet")
#include <iostream>
#include <fstream>
#include <string.h>

using std::cout;

int send(const char * ftp, const char * user, const char * pass, const char * pathondisk, const char * nameonftp)
{

    HINTERNET hInternet;
    HINTERNET hFtpSession;
    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if(hInternet==NULL)
    {
        cout << GetLastError();
        //system("PAUSE");
        return 1;
    }
    hFtpSession = InternetConnectA(hInternet,
        ftp, INTERNET_DEFAULT_FTP_PORT,
        user, pass, INTERNET_SERVICE_FTP,
        INTERNET_FLAG_PASSIVE, 0);
    if(hFtpSession==NULL)
    {
        cout << GetLastError();
        //system("PAUSE");
        return 1;
    }
    Sleep(1000);
    char * buf=new char[strlen(nameonftp) + 4 + 1];
    strcpy(buf, nameonftp);
    strcat(buf, ".txt");
    if (!FtpPutFileA(hFtpSession, pathondisk, buf, FTP_TRANSFER_TYPE_ASCII, 0)) {
        cout << GetLastError();
        delete[] buf;
        return 1;
    }
    delete[] buf;
    Sleep(1000);
    InternetCloseHandle(hFtpSession);
    InternetCloseHandle(hInternet);
    return 0;
}

int main() {
    send("127.0.0.1", "testuser", "test", "file.pdf", "backup");
    return 0;
}