H
// FTPSock.h: interface for the CFTPSock class.
//
///
#if !defined(AFX_FTPSOCK_H__E3C92278_9240_4DAE_9A90_3D316528BFD1__INCLUDED_)
#define AFX_FTPSOCK_H__E3C92278_9240_4DAE_9A90_3D316528BFD1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//SOCKET
#include <winsock2.h>
#pragma comment(lib, "WS2_32.LIB")
#include <mmsystem.h> // timeGetTime 定义1毫秒和2秒时钟间隔,以毫秒为单位
#pragma comment(lib,"Winmm.lib")
//CFile
#include <fstream.h>
#define UINT_TRUE 0
#define UINT_FLASE 1
//FTP char buffer[] Array Size
#define BUFF_RECV 1024
#define BUFF_UPLOAD 8*1024
#define BUFF_DOWNLOAD 4095
#define BUFFER_BLOCK_SIZE 1024
//Exception Happen Error
#define CheckERR(x) if (FAILED(hr=(x))) {CFTPSock::Msg(TEXT("FAILED(hr=0x%x) in ") TEXT(#x) TEXT("\n\0"), hr); return hr;}
#define TransTimeFormat _T("%H:%M:%S")
#define TimeDate _T("%Y%m%d%H%M%S")
class CFTPSock
{
//Attributes
public:
//===========[FTP Link Comm Var]==================================
static CString szFTPIP;
static CString szFTPPort;
static CString szFTPUserName;
static CString szFTPUserPWD;
static CString szFTPUserFolderPath;
static CString szFTPPath; //客户端给用户的文件夹
static CString szLogFileName;//Local FTP Log
static CString szFTPUserFolderPathFull; //user full folder path
//============[FTP Server Response Code]============================
static int iFTPResponse_DEL_Folder;
static int iFTPResponse_RETR;
static int iFTPResponse_REST;
static int iFTPResponse_Login_User ;
static int iFTPResponse_Login_Password;
static int iFTPResponse_Connect;
static int iFTPResponse_DisConnec;
static int iFTPResponse_SendFile;
static int iFTPResponse_GetCurDir;
static int iFTPResponse_CreateFolder;
static int iFTPResponse_SetCurDir;
static int iFTPResponse_TYPE;
static int iFTPResponse_PASV_Port;
static int iFTPResponse_STOR;
static int iFTPResponse_TransComplete;
static int iFTPResponse_SIZE;
static int iFTPResponse_APPE;
/************************************************************************/
/* 传递一个文件的文件属性 */
/************************************************************************/
static struct STRUFile
{
//===Local File Attributes==================
CString szFileFullNameLocal; // Full Path and File Name
CString szFileDescLocal; // File Description
CString szFileSizeLocal;
int iFileSizeLocal;
//===Remote File Attributes==================
CString szFolderRemote;
CString szFileSizeRemote;
int iFileSizeRemote;
CString szFileNameRemote; // 只有文件名和后缀名的 ServerFileName=LocalFileName
//===Trans Information=========================
CString szSizeTrans; // 已经传送的文件大小
CString szSizeRest; // 剩余文件大小
int iFilePos;
CString szTimeStart; //Default NULL;
CTime timeStart;
CString szTimeEnd; //Default NULL;
CTime timeEnd;
CString szTimeTrans;
//Percent Information
DOUBLE iPercent; // Default=0;
CString szPercent; // Show
int iPercentMax; // Default = 100;
int iPercentMin; // Default = 0;
BOOL bIfReTrans; //Default TRUE is ReTrans,
CString szMessage;
int iDelaySleep; //must be =0;
//===============Time Sign ============================================
CString szHourSign;// Default:Hours
CString szMinSign; // Default:Minutes
CString szSecSign; // Default:Second
};
/************************************************************************/
/* 传送文件的主要结构体 */
/************************************************************************/
static struct STRUFTPList
{
//=====Connect and Login==============================================
CString szFTPServerIP;
CString szUser;
CString szPWD;
CString szPort;
BOOL bIsDownload; // True = Download else Upload
CString szIsDownload_Caption; //表示当前在下在或者在上传数据
//==============Log Show===============================================
CString szFileLog; // 日志文件,如果是NULL,表示不要日志
int iLineNoMessage; // 日志的初始化 =0
CString szMessage; // 日志的每行信息,或者外界显示当前传递的情况
//===============Time Sign ============================================
CString szHourSign;// Default:Hours
CString szMinSign; // Default:Minutes
CString szSecSign; // Default:Second
CString szTimeStart; //Default NULL;
CTime timeStart;
CString szTimeEnd; //Default NULL;
CTime timeEnd;
CString szTimeTrans;
//Percent Information
DOUBLE iPercent; // Default=0;
CString szPercent; // Show
int iPercentMax; // Default = 100;
int iPercentMin; // Default = 100;
CArray<STRUFile,STRUFile&> struFileArray;
BOOL bFinished;
};
//=============[SOCKET]===============================
private:
static SOCKET socketSendFile;
static SOCKET socketListen;
//Function
public:
CFTPSock();
virtual ~CFTPSock();
//打开服务器 + 传送多个文件 +关闭FTP Link [upload and download]
static UINT ThreadFTPTrans(LPVOID pParam);
static CString GetCreateFileNameUID(CString szID);
private:
//Open FTP Server
static BOOL ConnectServer(CString szServerIP,CString szPort,CString &szOutMSG);
static BOOL DisconnectServer(CString &szMessage);
static BOOL LoginUserName(CString szUserName,CString &szOutMSG);
static BOOL LoginUserPWD(CString szPWD,CString &szOutMSG);
static BOOL SendCommand(SOCKET listenSock,CString szCommand,int iResponseCodeSuccessfully, CString &szOutMSG);
static BOOL CreateFolderInServer(CString szCurDir,CString szFolder,CString &szOutMSG);
static BOOL CreateSocket(SOCKET &createSocket,CString szFTPServerIP,CString szPortMessage);
static int GetSendFilePortFormFTPServer(CString szNewPort);
static BOOL GetFTPServerResponseSuccessful(int iResponseCodeSuccessfully,CString &szOutMessage);
//传送文件函数
static BOOL FileMultiFileTrans(STRUFTPList *pInfo);
//Upload
static BOOL FileUpload(STRUFile *pFile,CString szFTPServerIP,int iLineNoMessage,CString szFileLog);
static BOOL TransFileToServer(SOCKET &mlistenSock,STRUFile *pSTRUFile,int iLineNoMessage,CString szFileLog);
//Download
static BOOL TransFileToLocal(SOCKET &mlistenSock,STRUFile *pSTRUFile,int iLineNoMessage,CString szFileLog);
static BOOL FileDownload(STRUFile *pFile,CString szFTPServerIP,int iLineNoMessage,CString szFileLog);
//日志文件[得到移行数据]
static CString GetLogLine(int &iLineNo,CString szMessage);
//写一行细心到日志中去
static void logFile(int &iLineNo,CString szFileNameLog,CString szMessage,CString &szOut_Message);
//Others
static int GetFileSizeInt(CString szFileName);
static CString GetFileSizeConvent(int iDataSize);
static CString GetTimeSpan(CTime timeStart, CString szHourSign, CString szMinSign, CString szSecSign);
static CString GetTimeSpanTIMEFormat(CTime timeStart);
static BOOL DeleteOneFile(CString File);
static BOOL CreateNewFile(CString szFileName);
static BOOL IsExistFile(CString szFileName);
};
#endif // !defined(AFX_FTPSOCK_H__E3C92278_9240_4DAE_9A90_3D316528BFD1__INCLUDED_)
CPP
// FTPSock.cpp: implementation of the CFTPSock class.
//
//
#include "stdafx.h"
#include "FTPSock.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
// Construction/Destruction
//
#define Debug_DelaySleepTime 0
//===========[FTP Link Comm Var]==================================
CString CFTPSock::szFTPIP=_T("");
CString CFTPSock::szFTPPort=_T("");
CString CFTPSock::szFTPUserName=_T("");
CString CFTPSock::szFTPUserPWD=_T("");
CString CFTPSock::szFTPUserFolderPath=_T("");
CString CFTPSock::szFTPPath=_T("");
CString CFTPSock::szLogFileName = _T("");
CString CFTPSock::szFTPUserFolderPathFull=_T("");
//============[FTP Response Code]=================================
int CFTPSock::iFTPResponse_RETR = 100;
int CFTPSock::iFTPResponse_REST=100;
int CFTPSock::iFTPResponse_DEL_Folder = 250;
int CFTPSock::iFTPResponse_TransComplete = 226;
int CFTPSock::iFTPResponse_Connect = 220;
int CFTPSock::iFTPResponse_DisConnec = 221;
int CFTPSock::iFTPResponse_Login_User = 331;
int CFTPSock::iFTPResponse_Login_Password = 230;
int CFTPSock::iFTPResponse_SendFile = 226;
int CFTPSock::iFTPResponse_GetCurDir = 257;
int CFTPSock::iFTPResponse_CreateFolder = 257;
int CFTPSock::iFTPResponse_SetCurDir = 250;
int CFTPSock::iFTPResponse_TYPE = 200;
int CFTPSock::iFTPResponse_PASV_Port = 227;
int CFTPSock::iFTPResponse_STOR = 150;
int CFTPSock::iFTPResponse_SIZE = 213;
int CFTPSock::iFTPResponse_APPE = 150;
//================[Socket COMM Listen]==================================
SOCKET CFTPSock::socketListen;
SOCKET CFTPSock::socketSendFile;
CFTPSock::CFTPSock()
{
}
CFTPSock::~CFTPSock()
{
}
//************************************
// Method: ThreadFTPConnectLogin
// FullName: CFTPSock::ThreadFTPConnectLogin
// Access: public
// Returns: UINT
// Qualifier: Line FTP and User PWD
// Parameter: LPVOID pParam (STRUFTPConnLogin)
//************************************
UINT CFTPSock::ThreadFTPTrans(LPVOID pParam)
{
STRUFTPList *pInfo = (STRUFTPList *)pParam;
pInfo->bFinished = FALSE;
pInfo->timeStart = CTime::GetCurrentTime();
pInfo->szTimeStart = pInfo->timeStart.Format(TransTimeFormat);
BOOL bFlag=FALSE;
CString szOut_Message=_T("");
//========================Connect FTP Server==========================================
pInfo->szMessage = _T("Start Link Server Computer in network,Please wait a few minutes.");
bFlag = CFTPSock::ConnectServer(pInfo->szFTPServerIP,pInfo->szPort,pInfo->szMessage);
if (bFlag==TRUE)
{
pInfo->szMessage=_T("link server successfully");
//AfxMessageBox(pInfo->szMessage);
}
else
{
pInfo->szMessage=_T("link server Failed!");
}
CFTPSock::logFile(pInfo->iLineNoMessage,pInfo->szFileLog,pInfo->szMessage,szOut_Message);
if(FAILED(bFlag))
{
WSACleanup();
return UINT_FLASE;
}
//=======================Login User ================================================
bFlag = CFTPSock::LoginUserName(pInfo->szUser,pInfo->szMessage);
if (bFlag==TRUE)
{
pInfo->szMessage=_T("User Login successfully");
}
else
{
pInfo->szMessage=_T("User Login Failed!");
}
CFTPSock::logFile(pInfo->iLineNoMessage,pInfo->szFileLog,pInfo->szMessage,szOut_Message);
if(FAILED(bFlag))
{
WSACleanup();
return UINT_FLASE;
}
//==================== Login Password===============================================
bFlag = CFTPSock::LoginUserPWD(pInfo->szPWD,pInfo->szMessage);
if (bFlag==TRUE)
{
pInfo->szMessage=_T("User Password is correct!");
}
else
{
pInfo->szMessage=_T("User Password is wrong!");
}
CFTPSock::logFile(pInfo->iLineNoMessage,pInfo->szFileLog,pInfo->szMessage,szOut_Message);
if(FAILED(bFlag))
{
WSACleanup();
return UINT_FLASE;
}
//====================Trans One File(Not BreakDot UploadFile)============================
bFlag = CFTPSock::FileMultiFileTrans(pInfo);
if(FAILED(bFlag))
{
WSACleanup();
return UINT_FLASE;
}
//====================Close FTP Connect =================================================
bFlag = CFTPSock::DisconnectServer(pInfo->szMessage);
if(FAILED(bFlag))
{
WSACleanup();
pInfo->szMessage =_T("Connect Server Failed!");
CFTPSock::logFile(pInfo->iLineNoMessage,pInfo->szFileLog,pInfo->szMessage,szOut_Message);
return UINT_FLASE;
}
pInfo->szMessage = _T("Close Server Computer link,this trans finished!");
CFTPSock::logFile(pInfo->iLineNoMessage,pInfo->szFileLog,pInfo->szMessage,szOut_Message);
pInfo->bFinished=TRUE;
return UINT_TRUE;
}
//************************************
// Method: ConnectServer
// FullName: CFTPSocketClient::ConnectServer
// Access: public
// Returns: BOOL
// Qualifier: Connect FTP Server (PC install FTPServer software)
// Parameter: CString szFTPServerIP
// Parameter: int iPort
//************************************
BOOL CFTPSock::ConnectServer(CString szServerIP,CString szPort,CString &szOutMSG)
{
//=======Get iPort =======================================================
int iPort=0;
iPort = _ttoi(szPort);
//========Get IP ANSI and UNICODE is OK For IP is Simple Char =========
char ch_ServerIP[17]={0};
int iLen = 0;
iLen = szServerIP.GetLength();
for (int i=0;i<iLen;i++)
{
ch_ServerIP[i] = (char)szServerIP.GetAt(i); // szFTPServerIP[i]; //warring (LPCTSTR)
}
ch_ServerIP[iLen]='\0'; //Must be End
//==========Return Message about connect ip
szOutMSG += _T(" Connect IP:") + szServerIP ;
szOutMSG += _T(" Port:") + szPort;
//=============ini Socket Var====================
WSADATA data;
if(WSAStartup(MAKEWORD(2,2), &data)!=0)
{
WSACleanup();
szOutMSG += _T("\r\n WSAStartup Failed! \r\n ");
return FALSE;
}
socketListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // or IPPROTO_IP
//==============FTP Parameter setting ======================
sockaddr_in servAddr; //Socket Connect var
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(iPort);
servAddr.sin_addr.S_un.S_addr = inet_addr(ch_ServerIP);
if(::connect(CFTPSock::socketListen, (const sockaddr*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
{
closesocket(CFTPSock::socketListen);
WSACleanup();
szOutMSG += _T("\r\n connect Error! ");
return FALSE;
}
//delete []&ch_ServerIP; //Debug error
//================Response if Connect successfully Message =======================
char sendbuf[BUFF_RECV]={0};
int i_recvCode =0 ;
i_recvCode = recv(socketListen,sendbuf,BUFF_RECV,0);
sendbuf[i_recvCode] = '\0';
if(i_recvCode == SOCKET_ERROR)
{
closesocket(CFTPSock::socketListen);
WSACleanup();
szOutMSG += _T("\r\n connect failed! ");
szOutMSG += sendbuf;
return FALSE;
}
szOutMSG += _T("\r\n ");
szOutMSG += sendbuf;
return TRUE;
}
//************************************
// Method: DisconnectFTPServer
// FullName: CFTPSocketClient::DisconnectFTPServer
// Access: public
// Returns: int
// Qualifier: Connect not to link
//************************************
BOOL CFTPSock::DisconnectServer(CString &szMessage)
{
BOOL bFlag=FALSE;
CString szCommand=_T("");
szCommand = _T("QUIT\r\n");
bFlag = SendCommand(CFTPSock::socketListen,szCommand,CFTPSock::iFTPResponse_DisConnec,szMessage);
szMessage = _T(" ") + szMessage;
WSACleanup();
return bFlag;
}
//************************************
// Method: LoginUserName
// FullName: CFTPSocketClient::LoginUserName
// Access: public
// Returns: int
// Qualifier: Login User Name
// Parameter: CString szUserName
//************************************
BOOL CFTPSock::LoginUserName(CString szUserName,CString &szOutMSG)
{
BOOL bFlag=FALSE;
CString szCommand=_T("");
szCommand = _T("USER ");
szCommand += szUserName;
szCommand +=_T("\r\n");
bFlag = SendCommand(CFTPSock::socketListen,szCommand,CFTPSock::iFTPResponse_Login_User,szOutMSG);
szOutMSG =_T(" ") + szOutMSG;
return bFlag;
}
//************************************
// Method: LoginUserPWD
// FullName: CFTPSocketClient::LoginUserPWD
// Access: public
// Returns: int
// Qualifier: Login User Password
// Parameter: CString szPWD
//************************************
BOOL CFTPSock::LoginUserPWD(CString szPWD,CString &szOutMSG)
{
BOOL bFlag=FALSE;
CString szCommand=_T("");
szCommand = _T("PASS ");
szCommand += szPWD;
szCommand +=_T("\r\n");
bFlag = SendCommand(CFTPSock::socketListen,szCommand,CFTPSock::iFTPResponse_Login_Password,szOutMSG);
szOutMSG =_T(" ") + szOutMSG;
return bFlag;
}
//************************************
// Method: SendCommand
// FullName: CFTPSocketClient::SendCommand
// Access: public
// Returns: BOOL
// Qualifier: 发送命令+传送的信息(中文和字母)
// Parameter: SOCKET listenSock
// Parameter: CString szCommand
// Parameter: CString & szRecvMessage OUT
//************************************
BOOL CFTPSock::SendCommand(SOCKET listenSock,CString szCommand,int iResponseCodeSuccessfully,
CString &szOutMSG)
{
char sendbuf[BUFF_RECV]={0};
int iLength = 0;
BOOL bSendFlag=FALSE;
#ifdef _UNICODE
iLength = WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK, szCommand.GetBuffer(0),-1,sendbuf,
BUFF_RECV,NULL,NULL);
#else
iLength = szCommand.GetLength();
for (int i=0;i<iLength;i++)
{
sendbuf[i]=(char)szCommand[i];
}
#endif
sendbuf[iLength]='\0';
send(listenSock, sendbuf,iLength, 0);
int i_recvCode =0;
i_recvCode = recv(listenSock,sendbuf,BUFF_RECV,0);
sendbuf[i_recvCode] = '\0';
if(i_recvCode == SOCKET_ERROR || i_recvCode ==0)
{
bSendFlag =FALSE;
}
else
{
//判断是否和反馈码相同 iResponseCodeSuccessfully
CString szResponseCode=_T("");
szResponseCode = sendbuf;
szResponseCode = szResponseCode.Mid(0,3);
int iResponseCode=0;
iResponseCode = _ttoi(szResponseCode);
if (iResponseCode == iResponseCodeSuccessfully)
{
bSendFlag = TRUE;
}
else
{
bSendFlag = FALSE;
}
}
szOutMSG = sendbuf;
return bSendFlag;
}
void CFTPSock::logFile(int &iLineNo,CString szFileNameLog,CString szMessage,CString &szOut_Message)
{
CString szline=_T("");
szline = CFTPSock::GetLogLine(iLineNo,szMessage);
szOut_Message = szline;
CFile file_log;
BOOL bFlag = file_log.Open(szFileNameLog,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite);
if (bFlag==FALSE)
{
return;
}
char buffer[BUFF_RECV]={0};
int iLength = 0;
#ifdef _UNICODE
iLength = WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK, szline.GetBuffer(0),-1,buffer,
BUFF_RECV,NULL,NULL);
#else
iLength = szline.GetLength();
for (int i=0;i<iLength;i++)
{
buffer[i]=(char)szline[i];
}
#endif
buffer[iLength]='\0';
file_log.SeekToEnd();
file_log.Write(buffer,iLength);
file_log.Flush();
file_log.Close();
}
//************************************
// Method: GetListLineText
// FullName: CFTPSocketClient::GetListLineText
// Access: public
// Returns: CString
// Qualifier: Get Line Text
// Parameter: CListBox & listBox
// Parameter: CString szNow
// Parameter: CString szMessage
//************************************
CString CFTPSock::GetLogLine(int &iLineNo,CString szMessage)
{
CString szNow=_T("");
COleDateTime dateTime= COleDateTime::GetCurrentTime();
szNow = dateTime.Format(_T("%H:%M:%S %A, %B %d, %Y"));
CString szLine=_T("");
CString szCount = _T("");
iLineNo++;
szCount.Format(_T("%d"),iLineNo);
if (iLineNo == 1)
{
szLine = _T("[");
}
else
{
szLine = _T("\r\n[");
}
szLine += szCount;
szLine += _T("]");
szLine += szNow;
szLine += _T("\r\n ");
szLine += szMessage;
return szLine;
}
BOOL CFTPSock::FileMultiFileTrans(STRUFTPList *pInfo)
{
int iFileCount=0;
iFileCount = pInfo->struFileArray.GetSize();
BOOL bFlag = FALSE;
for (int iFilePos=0; iFilePos<iFileCount; iFilePos++)
{
if (pInfo->bIsDownload==TRUE)
{
if(pInfo->struFileArray[iFilePos].szFileNameRemote.GetLength()>0)
{
bFlag = FileDownload(&pInfo->struFileArray[iFilePos],pInfo->szFTPServerIP,pInfo->iLineNoMessage,pInfo->szFileLog);
}
}
else
{
if(pInfo->struFileArray[iFilePos].szFileFullNameLocal.GetLength()>0)
{
bFlag = FileUpload(&pInfo->struFileArray[iFilePos],pInfo->szFTPServerIP,pInfo->iLineNoMessage,pInfo->szFileLog);
}
}
if (bFlag==FALSE)
{
break;
}
bFlag=TRUE;
}
return bFlag;
}
BOOL CFTPSock::FileUpload(STRUFile *pFile,CString szFTPServerIP,int iLineNoMessage,CString szFileLog)
{
CString szTempLog=_T("");
CString szCommandSendFile=_T("");
CString szMessage=_T("");
BOOL bFlag=FALSE;
pFile->timeStart = CTime::GetCurrentTime();
pFile->szTimeStart = pFile->timeStart.Format(TransTimeFormat);
//[第一步] [获得本地文件大小] 主要是断点续传 或者显示 UI 传送量信息
pFile->iFileSizeLocal = CFTPSock::GetFileSizeInt(pFile->szFileFullNameLocal);
pFile->szMessage = _T(" Get Size From:")+ pFile->szFileFullNameLocal;
//显示在UI信息上
pFile->szFileSizeLocal.Format(_T("%s"),CFTPSock::GetFileSizeConvent(pFile->iFileSizeLocal));
// 如果在服务器上,建立指定的路径,开始设定好默认的路径,然后在之上建立文件夹,必定会成功,
// 失败说明已经建立了这个文件夹
//AfxMessageBox(pFile->szFolderRemote);
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szFileSizeLocal,szTempLog);
if (CFTPSock::CreateFolderInServer(pFile->szFolderRemote,pFile->szMessage,szTempLog)==FALSE)
{
}
else
{
pFile->szMessage = _T("Create Folder in Successfully!");
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
}
//CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
//到这个路径目录中去
CString szCWDRemoteDirectory = _T("CWD ") + pFile->szFolderRemote +_T("\r\n");
bFlag=CFTPSock::SendCommand(CFTPSock::socketListen,szCWDRemoteDirectory,CFTPSock::iFTPResponse_TYPE,pFile->szMessage);
//TYPE A UNICODE.TXT I E
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
if (pFile->szMessage.Mid(0,3)==_T("250"))
{
pFile->szMessage = _T("Go to directory is successfully!");
}
else
{
AfxMessageBox(_T("Path is Not Exist"));
return FALSE;
}
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
if (pFile->szFileNameRemote.GetLength()<=0)
{
pFile->szFileNameRemote = CFileOperator::GetFileName(pFile->szFileFullNameLocal);
}
if (pFile->bIfReTrans==FALSE)
{ //不重新传递==断点续传
//=========[ Get FTPServer File Size ] =============================================
szCommandSendFile = _T("SIZE ") + pFile->szFileNameRemote;
szCommandSendFile +=_T("\r\n");
CFTPSock::SendCommand(CFTPSock::socketListen,szCommandSendFile,CFTPSock::iFTPResponse_SIZE,pFile->szMessage);
pFile->szFileSizeRemote = pFile->szMessage.Mid(4,pFile->szMessage.GetLength()-4);
pFile->iFileSizeRemote = _ttoi(pFile->szFileSizeRemote);
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
if (pFile->iFileSizeRemote == pFile->iFileSizeLocal)
{
//已经传送完毕
pFile->szMessage = _T("This File Size = FTP Server File Size.");
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
return TRUE;
}
else
{
//Break Dot Upload File ,从断点位置,开始上传数据
pFile->iFilePos = pFile->iFileSizeRemote;
}
}
else
{
//重新上传数据
pFile->iFilePos = 0; //表示从新传递,文件位置从0开始
pFile->iFileSizeRemote = 0;
}
CFTPSock::SendCommand(CFTPSock::socketListen,_T("TYPE A\r\n"),CFTPSock::iFTPResponse_TYPE,pFile->szMessage); //TYPE A UNICODE.TXT I E
//CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
CString szNewIPPort=_T("");
CFTPSock::SendCommand(CFTPSock::socketListen,_T("PASV \r\n"),CFTPSock::iFTPResponse_PASV_Port,szNewIPPort);//PASV I
//Create Socket For UPLOAD FILE
CreateSocket(socketSendFile,szFTPServerIP,szNewIPPort);
//STOR UpdateFile Command Before must be create socketSend
if (pFile->bIfReTrans==TRUE)
{
szCommandSendFile = _T("STOR ") + pFile->szFileNameRemote +_T("\r\n");
}
else
{
szCommandSendFile = _T("APPE ") + pFile->szFileNameRemote +_T("\r\n");
}
CFTPSock::SendCommand(CFTPSock::socketListen,szCommandSendFile,CFTPSock::iFTPResponse_STOR,pFile->szMessage);
szMessage=_T("Start Trans File");
CFTPSock::logFile(iLineNoMessage,szFileLog,szMessage,szTempLog);
//Sleep(1000);
bFlag = CFTPSock::TransFileToServer(socketSendFile,pFile,iLineNoMessage,szFileLog);
pFile->szMessage=_T("Trans File to server finished");
return bFlag;
}
//UNICODE and DEBUG All OK
BOOL CFTPSock::TransFileToServer(SOCKET &mlistenSock,STRUFile *pSTRUFile,int iLineNoMessage,CString szFileLog)
{
int iSendTotal=pSTRUFile->iFileSizeRemote;
int iSendCount =BUFF_UPLOAD;
INT iCount=0;
//====================计算出百分数中每份的数据==========================
LPCTSTR filename= pSTRUFile->szFileFullNameLocal;
DOUBLE iPerUnitSize = pSTRUFile->iFileSizeLocal / pSTRUFile->iPercentMax;
DOUBLE iPerUnitSizeRest = pSTRUFile->iFileSizeLocal % pSTRUFile->iPercentMax * 0.01;
iPerUnitSize+= iPerUnitSizeRest ;
DOUBLE iPercent=0;
CString szPercent=_T("");
CString szMessageOut=_T("");
//===================打开本地文件传递===================================
CString szMessage=_T("");
CFile cfile;
int nRead= BUFF_UPLOAD ;
char buffer[BUFF_UPLOAD]={0};
//BOOL bFileOpenFlag = cfile.Open(filename, CFile::modeRead | CFile::modeNoTruncate);
BOOL bFileOpenFlag = cfile.Open(filename, CFile::modeRead | CFile::shareDenyWrite);
if (pSTRUFile->iFilePos<=0)
{
pSTRUFile->iFilePos=0;
}
if (bFileOpenFlag==FALSE)
{
pSTRUFile->szMessage =_T("Can not Open File:");
pSTRUFile->szMessage += filename;
CFTPSock::logFile(iLineNoMessage,szFileLog,pSTRUFile->szMessage,szMessageOut);
closesocket(mlistenSock);
return FALSE;
}
else
{
int iRestSize=0;
CString szTemp=_T("");
int iPos = cfile.Seek(pSTRUFile->iFilePos,SEEK_CUR);
while(nRead == BUFF_UPLOAD )
{
iCount++;
if (iCount==2)
{
//Sleep(pSTRUFile->iDelaySleep);//上传不需要延迟,可以达到每秒40多k
}
nRead = cfile.Read(buffer, BUFF_UPLOAD);
iSendCount = send(mlistenSock,buffer,nRead,0);
iSendTotal +=iSendCount;
iRestSize = pSTRUFile->iFileSizeLocal - iSendTotal;
//计算百分号
iPercent = iSendTotal / iPerUnitSize; //iPercentSize;
szPercent.Format((LPCTSTR)_T("%.2f%%"),iPercent);
pSTRUFile->iPercent = iPercent;
pSTRUFile->szPercent= szPercent;
//pSTRUFile->timeEnd = CTime::GetCurrentTime();
// szTemp=CFTPSock::GetTimeSpan(pSTRUFile->timeStart,pSTRUFile->szHourSign,
// pSTRUFile->szMinSign,pSTRUFile->szSecSign);
szTemp=CFTPSock::GetTimeSpanTIMEFormat(pSTRUFile->timeStart);
if (szTemp.GetLength()>0)
{
pSTRUFile->szTimeTrans = szTemp;
//AfxMessageBox(szTemp);
}
//Show in Control
pSTRUFile->szSizeTrans = CFTPSock::GetFileSizeConvent(iSendTotal);
pSTRUFile->szSizeRest = CFTPSock::GetFileSizeConvent(iRestSize);
}
}
cfile.Close();
closesocket(mlistenSock);
BOOL bSendFlag =FALSE;
// 得到是否传送成功信息
bSendFlag = CFTPSock::GetFTPServerResponseSuccessful(CFTPSock::iFTPResponse_TransComplete,pSTRUFile->szMessage);
CFTPSock::logFile(iLineNoMessage,szFileLog,pSTRUFile->szMessage,szMessageOut);
pSTRUFile->szMessage=_T("Trans Data Finished!");
CFTPSock::logFile(iLineNoMessage,szFileLog,pSTRUFile->szMessage,szMessageOut);
return bSendFlag;
}
BOOL CFTPSock::CreateSocket(SOCKET &createSocket,CString szFTPServerIP,CString szPortMessage)
{
int iNewPort = 0;
iNewPort = GetSendFilePortFormFTPServer(szPortMessage);
SOCKADDR_IN l_sockaddr;
l_sockaddr.sin_family = AF_INET;
l_sockaddr.sin_port = htons(iNewPort);
//========Get IP ========================================================
char ch_ServerIP[100]={0};
int iLen = szFTPServerIP.GetLength();
for (int i=0;i<iLen;i++)
{
ch_ServerIP[i] = (char)szFTPServerIP[i];
}
ch_ServerIP[iLen]='\0'; //Must be End
l_sockaddr.sin_addr.S_un.S_addr = inet_addr(ch_ServerIP);
createSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(createSocket,(struct sockaddr *)&l_sockaddr,sizeof(l_sockaddr));
return TRUE;
}
int CFTPSock::GetFileSizeInt(CString szFileName)
{
CString szMessage=_T("");
int iFileSize=0;
CString szFileSize=_T("");
//获得本地文件大小
HANDLE hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
szMessage.Format(_T("\r\n Open File: %s is Failed!"),szFileName);
return 0;
}
// 取到本地文件大小,防止传送Server的 File位置 >本地文件,
iFileSize= GetFileSize(hFile, NULL); //hFile 自有的属性
CloseHandle(hFile);
return iFileSize;
}
CString CFTPSock::GetFileSizeConvent(int iDataSize)
{
DOUBLE iFileSize=0;
DOUBLE iUnit= 1024;
CString szFileSize=_T("0");
DOUBLE iMSize=0;
DOUBLE iKSize=0;
DOUBLE iBSize=0;
iMSize = iDataSize / iUnit /iUnit;
if (iMSize>1)
{
szFileSize.Format((LPCTSTR)_T("%.2fMB"),iMSize);
return szFileSize;
}
iKSize = iDataSize / iUnit ;
if (iKSize>1)
{
szFileSize.Format((LPCTSTR)_T("%.2fKB"),iKSize);
return szFileSize;
}
iBSize = iDataSize ;
if (iBSize>0)
{
szFileSize.Format((LPCTSTR)_T("%.2fB"),iBSize);
return szFileSize;
}
return szFileSize;
}
BOOL CFTPSock::CreateFolderInServer(CString szCurDir,CString szFolder,CString &szOutMSG)
{
if (szCurDir.GetLength()==1)
{
szCurDir=_T("/");
}
CString szServerCurDir=_T("");
CString szCommand =_T("");
szCommand = _T("MKD ") +szCurDir;
//szCommand += _T("/") + szFolder;
szCommand += _T("\r\n");
//AfxMessageBox(szCommand);
CString szTemp=_T("");
BOOL bFlag = SendCommand(CFTPSock::socketListen,szCommand,CFTPSock::iFTPResponse_CreateFolder,szTemp);
szOutMSG =_T("\r\n ") + szTemp;
return bFlag;
}
int CFTPSock::GetSendFilePortFormFTPServer(CString szNewPort)
{
int iPort = 0;
int iMid =256;
CString szPortMain=_T("");
CString szPortAdd=_T("");
int iCount=0;
int iPos=0;
CString szValue = szNewPort;
CString szTemp=_T("");
szTemp = szNewPort.Mid(0,3);
if (szTemp!=_T("227"))
{
return -1;
}
for (int i=0;i<szValue.GetLength();i++)
{
iPos = szValue.Find(_T(","));
if (iPos>-1)
{
iCount++;
szValue = szValue.Mid(iPos+1);
}
if (iCount == 4)
{
// szPortMain
szPortMain = szValue.Mid(0,szValue.Find(_T(",")));
//AfxMessageBox(szPortMain);
}
if (iCount == 5)
{
// szPortAdd
szPortAdd = szValue.Mid(0,szValue.GetLength()-3);
//AfxMessageBox(szPortAdd);
break;
}
}
int iPortMain=0;
int iPortAdd=0;
iPortMain = _ttoi(szPortMain);
iPortAdd = _ttoi(szPortAdd);
iPort = iPortMain * iMid;
iPort +=iPortAdd;
return iPort;
}
CString CFTPSock::GetTimeSpan(CTime timeStart, CString szHourSign, CString szMinSign, CString szSecSign)
{
int iSecondsRest=0;
int iOneHoursSec=60*60;
int iOneMinSec=60;
CString szTemp=_T("");
CString szHour=_T("");
CString szMin=_T("");
CString szSec=_T("");
CTime timeEnd = CTime::GetCurrentTime();
// 两个CTime相减得到CTimeSpan
CTimeSpan timeSpan = timeEnd - timeStart;
// 得到总的秒数
int nTSeconds = timeSpan.GetTotalSeconds();
int iSec = 0;
int iMin = 0;
int iHours =0;
CString szTimeSpan=_T("");
iHours = nTSeconds/iOneHoursSec;
iSecondsRest = nTSeconds - iHours*iOneHoursSec;
if (iHours>0)
{
szTemp.Format(_T("%d"),iHours);
szHour = szTemp + szHourSign;
}
iMin = iSecondsRest/iOneMinSec;
iSecondsRest = nTSeconds - iMin*iOneMinSec;
if (iMin>0)
{
szTemp.Format(_T("%d"),iMin);
szHour = szTemp + szMinSign;
}
iSec = iSecondsRest;
if (iSec>0)
{
szTemp.Format(_T("%d"),iSec);
szHour = szTemp + szSecSign;
}
szTimeSpan = szHour +szMin +szSec;
if (szTimeSpan.GetLength()<=0)
{
szTimeSpan.Format(_T("%d"),nTSeconds);
szTimeSpan +=szSecSign;
}
return szTimeSpan;
}
BOOL CFTPSock::GetFTPServerResponseSuccessful(int iResponseCodeSuccessfully,CString &szOutMessage)
{
//得到是否传送成功信息
char sendbuf[100];
int i_recvCode =0;
i_recvCode = recv(CFTPSock::socketListen,sendbuf,BUFF_RECV,0);
sendbuf[i_recvCode] = '\0';
szOutMessage +=_T("\r\n ");
szOutMessage += sendbuf;
BOOL bSendFlag =FALSE;
if(i_recvCode == SOCKET_ERROR || i_recvCode ==0)
{
BOOL bSendFlag =FALSE;
}
else
{
//判断是否和反馈码相同 iResponseCodeSuccessfully
CString szResponseCode=_T("");
szResponseCode = sendbuf;
szResponseCode = szResponseCode.Mid(0,3);
int iResponseCode=0;
iResponseCode = _ttoi(szResponseCode);
if (iResponseCode == iResponseCodeSuccessfully)
{
bSendFlag = TRUE;
}
else
{
bSendFlag = FALSE;
}
}
return bSendFlag;
}
BOOL CFTPSock::FileDownload(STRUFile *pFile,CString szFTPServerIP,int iLineNoMessage,CString szFileLog)
{
CString szCommandSendFile=_T("");
CString szMessage=_T("");
CString szOutMessage=_T("");
CString szNewIPPort=_T("");
BOOL bFlag=FALSE;
CString szTempLog=_T("");
pFile->timeStart = CTime::GetCurrentTime();
pFile->szTimeStart = pFile->timeStart.Format(TransTimeFormat);
//获得本地文件大小
//检测本地文件是否存在
BOOL bFileExist = CFTPSock::IsExistFile(pFile->szFileFullNameLocal);
if (pFile->bIfReTrans==TRUE)
{
//AfxMessageBox(_T("删除已经存在的下载文件,每次从新下载文件"));
//删除这个文件,然后建立这个文件
DeleteOneFile(pFile->szFileFullNameLocal);
CreateNewFile(pFile->szFileFullNameLocal);
}
pFile->iFileSizeLocal=CFTPSock::GetFileSizeInt(pFile->szFileFullNameLocal);
CString szFileSize=_T("");
pFile->szFileSizeLocal.Format(_T("%s"),CFTPSock::GetFileSizeConvent(pFile->iFileSizeLocal));
//到这个路径目录中去
CString szCWDRemoteDirectory = _T("CWD ") + pFile->szFolderRemote +_T("\r\n");
bFlag=CFTPSock::SendCommand(CFTPSock::socketListen,szCWDRemoteDirectory,CFTPSock::iFTPResponse_TYPE,szMessage);
//TYPE A UNICODE.TXT I E
if (szMessage.Mid(0,3)==_T("250"))
{
pFile->szMessage = _T("Go to directory is successfully!");
}
else
{
pFile->szMessage = _T("Server Path is Not Exist");
return FALSE;
}
CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
// 获得FTPServer 文件大小
szCommandSendFile = _T("SIZE ") + pFile->szFileNameRemote;
szCommandSendFile +=_T("\r\n");
CFTPSock::SendCommand(CFTPSock::socketListen,szCommandSendFile,CFTPSock::iFTPResponse_SIZE,szMessage);
if (szMessage.Mid(0,3)==_T("550"))
{
szTempLog =pFile->szFileNameRemote+_T(" not exist in server!");
CFTPSock::logFile(iLineNoMessage,szFileLog,szTempLog,szOutMessage);
return FALSE;
}
CString szFTPServerFileSize = _T("");
szFTPServerFileSize = szMessage.Mid(4,pFile->szMessage.GetLength()-4);
int iFTPServerFileSize = _ttoi(szFTPServerFileSize);
pFile->iFileSizeRemote = iFTPServerFileSize;
pFile->szFileSizeLocal.Format(_T("%s"),CFTPSock::GetFileSizeConvent(iFTPServerFileSize));
if (pFile->iFileSizeRemote == pFile->iFileSizeLocal)
{
//已经传送完毕
szMessage = _T("This File Size = FTP Server File Size.");
CFTPSock::logFile(iLineNoMessage,szFileLog,szMessage,szTempLog);
return TRUE;
}
else
{
//Break Dot Upload File
if (pFile->bIfReTrans==FALSE)
{
pFile->iFilePos = pFile->iFileSizeLocal;
// pInfo->iFileSizeRemote = iFTPServerFileSize;
}
else
{
pFile->iFilePos = 0; //表示从新传递,文件位置从0开始
//pInfo->iFileSizeRemote =iFTPServerFileSize;
}
}
CFTPSock::SendCommand(CFTPSock::socketListen,_T("TYPE A\r\n"),CFTPSock::iFTPResponse_TYPE,szMessage); //TYPE A UNICODE.TXT I E
//CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
CFTPSock::SendCommand(CFTPSock::socketListen,_T("PASV \r\n"),CFTPSock::iFTPResponse_PASV_Port,szNewIPPort);//PASV I
//Create Socket For UPLOAD FILE
CreateSocket(socketSendFile,szFTPServerIP,szNewIPPort);
//STOR UpdateFile Command Before must be create socketSend
if (pFile->bIfReTrans==TRUE )
{
}
else
{
// Setting FTP FileLocation Pos
CString szFileSizeLocal=_T("");
szFileSizeLocal.Format(_T("%d"),pFile->iFileSizeLocal);
szCommandSendFile = _T("REST ") + szFileSizeLocal+_T("\r\n");
CFTPSock::SendCommand(CFTPSock::socketListen,szCommandSendFile,CFTPSock::iFTPResponse_REST,szMessage);
//CFTPSock::logFile(iLineNoMessage,szFileLog,szMessage,szTempLog);
}
szCommandSendFile = _T("RETR ") + pFile->szFileNameRemote +_T("\r\n");
CFTPSock::SendCommand(CFTPSock::socketListen,szCommandSendFile,CFTPSock::iFTPResponse_STOR,szMessage);
//CFTPSock::logFile(iLineNoMessage,szFileLog,pFile->szMessage,szTempLog);
bFlag = CFTPSock::TransFileToLocal(socketSendFile,pFile,iLineNoMessage,szFileLog);
return bFlag;
}
//UNICODE and DEBUG All OK
BOOL CFTPSock::TransFileToLocal(SOCKET &mlistenSock,STRUFile *pSTRUFile,int iLineNoMessage,CString szFileLog)
{
int iSendTotal=pSTRUFile->iFileSizeLocal;
int iSendCount = BUFF_DOWNLOAD;
INT iCount=0;
CString szMessageOut=_T("");
//====================计算出百分数中每份的数据==========================
//LPCTSTR filename= pSTRUFile->szFileNameFullPathLocal;
DOUBLE iPerUnitSize = pSTRUFile->iFileSizeRemote/ pSTRUFile->iPercentMax;
DOUBLE iPerUnitSizeRest = pSTRUFile->iFileSizeRemote % pSTRUFile->iPercentMax * 0.01;
iPerUnitSize+= iPerUnitSizeRest ;
DOUBLE iPercent=0;
CString szPercent=_T("");
//===================打开本地文件传递===================================
CString szMessage=_T("");
int nRead= BUFF_DOWNLOAD ;
char buffer[BUFF_DOWNLOAD+1]={0};
BOOL bFileOpenFlag=FALSE;
//Modify liulili
char chFile[BUFF_DOWNLOAD+1]={0};
int iLength = 0;
BOOL bSendFlag=FALSE;
CString szFileName = pSTRUFile->szFileFullNameLocal;
#ifdef _UNICODE
iLength = WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,
szFileName.GetBuffer(0),-1,chFile,
BUFF_DOWNLOAD,NULL,NULL);
#else
iLength = szFileName.GetLength();
for (int i=0;i<iLength;i++)
{
chFile[i]=(char)szFileName[i];
}
#endif
chFile[iLength]='\0';
int iRestSize=0;
CString szTemp=_T("");
ofstream cfile;
if (pSTRUFile->bIfReTrans==FALSE)
{
cfile.open(chFile, ios::binary|ios::app);
}
else
{
cfile.open(chFile, ios::binary);
}
if (pSTRUFile->iFilePos<=0)
{
pSTRUFile->iFilePos=0;
}
while(1)
{
// Wait to receive, nRet = NumberOfBytesReceived
nRead = recv(mlistenSock, buffer, sizeof(buffer), 0);
if (nRead == SOCKET_ERROR)
{
break;
}
if (nRead == 0)
{
break;
}
else
{
buffer[nRead]='\0';
cfile.write(buffer, nRead);
//Sleep(10);
cfile.flush();
iSendCount = nRead;
iSendTotal += iSendCount;
if ((iSendTotal>1024)&&(iSendTotal/(1024)>0))
{
iSendCount = nRead;
iSendTotal +=iSendCount;
iRestSize = pSTRUFile->iFileSizeRemote- iSendTotal;
//计算百分号
iPercent = iSendTotal / iPerUnitSize; //iPercentSize;
szPercent.Format((LPCTSTR)_T("%.2f%%"),iPercent);
pSTRUFile->iPercent=iPercent;
pSTRUFile->szPercent= szPercent;
pSTRUFile->timeEnd = CTime::GetCurrentTime();
// szTemp=CFTPSock::GetTimeSpan(pSTRUFile->timeStart,pSTRUFile->szHourSign,
// pSTRUFile->szMinSign,pSTRUFile->szSecSign);
szTemp=CFTPSock::GetTimeSpanTIMEFormat(pSTRUFile->timeStart);
if (szTemp.GetLength()>0)
{
pSTRUFile->szTimeTrans = szTemp;
}
//Show in Control
pSTRUFile->szSizeTrans = CFTPSock::GetFileSizeConvent(iSendTotal);
pSTRUFile->szSizeRest = CFTPSock::GetFileSizeConvent(iRestSize);
}
}
}
cfile.close();
closesocket(mlistenSock);
// 得到是否传送成功信息
bSendFlag = CFTPSock::GetFTPServerResponseSuccessful(CFTPSock::iFTPResponse_TransComplete,
pSTRUFile->szMessage);
CFTPSock::logFile(iLineNoMessage,szFileLog,pSTRUFile->szMessage,szMessageOut);
return bSendFlag;
}
//************************************
// Method: DeleteOneFile
// FullName: CFileOperator::DeleteOneFile
// Access: public
// Returns: BOOL
// Qualifier: Delete Folder Test Successfully!
// Parameter: CString File
//************************************
BOOL CFTPSock::DeleteOneFile(CString File)
{
if(DeleteFile((LPCTSTR)File)==TRUE)
{
return TRUE;
}
else
{
return FALSE;
}
}
BOOL CFTPSock::CreateNewFile(CString szFileName)
{
CFile file;
//Open File
if (file.Open(szFileName, CFile::modeCreate|CFile::modeNoTruncate)==FALSE)
{
return FALSE;
}
file.Close();
return TRUE;
}
//************************************
// Method: IsExistFile
// FullName: CFileOperator::IsExistFile
// Access: public
// Returns: BOOL
// Qualifier: 是否存在文件,检测文件是否存在
// Parameter: CString szFileName
//************************************
BOOL CFTPSock::IsExistFile(CString szFileName)
{
BOOL bFlag = FALSE;
LPWIN32_FIND_DATA lpFindFileData = new WIN32_FIND_DATA;
HANDLE hfile = FindFirstFile(szFileName,lpFindFileData);
delete lpFindFileData;
if(hfile==INVALID_HANDLE_VALUE)
{
bFlag = FALSE;
}
else
{
bFlag = TRUE;
}
FindClose(hfile);
return bFlag;
}
//************************************
// Method: GetCreateFileNameUID
// FullName: GetCreateFileNameUID
// Access: public
// Returns: CString
// Qualifier:
// Parameter: CString szID
//************************************
CString CFTPSock::GetCreateFileNameUID(CString szID)
{
CString szUID=_T("");
CTime tiem_now=CTime::GetCurrentTime();
CString szTime=_T("");
CString szMinSecond=_T("");
szTime = tiem_now.Format(TimeDate);
DWORD minSecond = timeGetTime();
szMinSecond.Format(_T("%000d"),minSecond);
szUID = szTime+szMinSecond+szID;
return szUID;
}
// 00:00:00 形式显示
CString CFTPSock::GetTimeSpanTIMEFormat(CTime timeStart)
{
int iSecondsRest=0;
int iOneHoursSec=60*60;
int iOneMinSec=60;
CString szTemp=_T("");
CString szHour=_T("");
CString szMin=_T("");
CString szSec=_T("");
CTime timeEnd = CTime::GetCurrentTime();
// 两个CTime相减得到CTimeSpan
CTimeSpan timeSpan = timeEnd - timeStart;
// 得到总的秒数
int nTSeconds = timeSpan.GetTotalSeconds();
int iSec = 0;
int iMin = 0;
int iHours =0;
CString szTimeSpan=_T("");
iHours = nTSeconds/iOneHoursSec;
iSecondsRest = nTSeconds - iHours*iOneHoursSec;
//Hours
if (iHours>0)
{
szTemp.Format(_T("%d"),iHours);
szHour = szTemp ;
if (szHour.GetLength()<=1)
{
szHour = _T("0")+szHour;
}
}
else
{
szHour =_T("00");
}
//Second
iMin = iSecondsRest/iOneMinSec;
iSecondsRest = nTSeconds - iMin*iOneMinSec;
if (iMin>0)
{
szTemp.Format(_T("%d"),iMin);
szMin = szTemp ;
if (szMin.GetLength()<=1)
{
szMin = _T("0")+szMin;
}
}
else
{
szMin =_T("00");
}
iSec = iSecondsRest;
if (iSec>0)
{
szTemp.Format(_T("%d"),iSec);
szSec = szTemp;
if (szSec.GetLength()<=1)
{
szSec = _T("0")+szSec;
}
}
else
{
szSec =_T("00");
}
szTimeSpan = szHour+_T(":") +szMin +_T(":")+szSec;
return szTimeSpan;
}