您的位置:首页 > 编程语言 > C语言/C++

C语言自动下载ftp文件程序

2010-01-13 16:22 477 查看
由于经常要到一个固定ftp下载几个文件,不想每次都重复登陆选择,因此用C写了一个简单的ftp自动下载程序。

从FTP 134.101.50.23/Mapper/CDMA/ 目录下下载命名以CDMA开始的文件到本地地址。

源代码如下:

#include <afx.h>
#include <afxwin.h>
#include <afxinet.h>
#include <stdio.h>

CWinApp theApp;

void main()
{
int iFileCnt =0;

if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
return;
}

// create a session object to initialize WININET library
CInternetSession sess(_T("MyProgram/1.0"));
CFtpConnection* pConnect = NULL;

try
{
// Request a connection to ftp Default with username = ANONYMOUS
// and password set to the machine name @ domain name

pConnect = sess.GetFtpConnection(_T("134.101.50.23"));

// use a file find object to find files
CFtpFileFind finder(pConnect);

//Set FTP directory
pConnect->SetCurrentDirectory(_T("/Mapper/CDMA"));

CString strDirName;
pConnect->GetCurrentDirectoryAsURL(strDirName);
// printf("GetCurrentDirectoryAsURL is : %s/n",strDirName);

CString strFileName,strObjFile;
//Set the directory where object file is put
CString strObjDir(_T("C:/Documents and Settings/Han Teng/桌面/CDMA map/"));

// Find files start with name CDMA
BOOL bWorking = finder.FindFile(_T("CDMA*"));
BOOL bGetFile;
while (bWorking)
{
bWorking = finder.FindNextFile();
// printf("GetFileURL: %s/n", (LPCTSTR) finder.GetFileURL());
strFileName = finder.GetFileURL();
strFileName = strFileName.Right(strFileName.GetLength()-strDirName.GetLength()-1);
// printf("FileName : %s/n", strFileName);
strObjFile = strObjDir + strFileName;
// printf("ObjFile : %s/n", strObjFile);

//Get file
bGetFile = pConnect->GetFile(strFileName,strObjFile,FALSE,
FILE_ATTRIBUTE_COMPRESSED,FTP_TRANSFER_TYPE_BINARY,1);
if(bGetFile == 0)
{
printf("Not get file! %s/n", strFileName);
}
else
{
printf("Get file done! %s/n",strFileName);
iFileCnt++;
}

}

}
catch (CInternetException* pEx)
{
TCHAR sz[1024];
pEx->GetErrorMessage(sz, 1024);
printf("ERROR! %s/n", sz);
pEx->Delete();
}

printf("%d files is download to local directory!/n",iFileCnt);

// if the connection is open, close it
if (pConnect != NULL)
pConnect->Close();
delete pConnect;

return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: