由于经常要到一个固定ftp下载几个文件,不想每次都重复登陆选择,因此用C写了一个简单的ftp自动下载程序。
从FTP 134.101.50.23/Mapper/CDMA/ 目录下下载命名以CDMA开始的文件到本地地址。
源代码如下:
#include
#include
#include
#include
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;}