2015-12-16 40 views
0

所以我發現這個C++程序,我想我會用它來自動備份我的文件到我的桌面ftp服務器,但它總是運行到相同的seg故障問題,檢查ftp服務器日誌我可以看到,實際上是連接到ftp服務器並使用用戶名和密碼登錄,但是當它到達實際上傳部分時,它會崩潰。在wininet ftp程序中遇到seg故障

我跑它通過開發的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

不要試圖修改字符串文字。即使它們是可修改的,'strcat(buf,「.txt」);'也會導致出界訪問。 – MikeCAT

+0

'cout << GetLastError(); //這是永遠不會達到的原因......因爲錯誤? – MikeCAT

+0

@MikeCAT是程序崩潰之前,它可以打印GetLastError();到控制檯。 –

回答

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; 
} 
+0

謝謝,這個作品,我明白你的意思了。 –