Ftp的断点下载实现

时间:2021-11-03 07:38:37

思路:首先获取本地临时文件的大小,在通过FTp的REST命令获取远程文件的偏移,然后再RETR命令在偏移处下载。while循环对比本地文件和远程文件的字节大小,如此

不断的反复以上过程,直到远程文件字节和本地文件字节一样,退出循环,下载完成。

    long remote_file_size = m_ftp->getFileLength(remoteFileName.toStdString());
long recvSize = ; if (remote_file_size == - )
{
return false;
} int conn_count = ; while (conn_count != && local_file_size != remote_file_size)
{
recvSize = m_ftp->Get2(remoteFileName.toStdString(), tmp_save_file_name.toStdString(), local_file_size);
if (recvSize <= )
{
msleep();
if (!reConnect())
{
break;
}
conn_count--;
} local_file_size = getLocalFileSize(tmp_save_file_name);
}
 FTP_API CFTP::Get2(const std::string &strRemoteFile, const std::string &strLocalFile, const int pos)
{
return downLoad2(strRemoteFile, strLocalFile, pos);
}
 FTP_API CFTP::downLoad2(const std::string &strRemoteFile, const std::string& strLocalFile, const int pos /*= 0*/, const unsigned int length /*= 0*/)
{
assert(length >= ); FILE *file = NULL;
unsigned long nDataLen = FTP_DEFAULT_BUFFER;
char strPos[MAX_PATH] = { };
int data_fd = socket(AF_INET, SOCK_STREAM, ); assert(data_fd != -); if ((length != ) && (length < nDataLen))
{
nDataLen = length;
}
char *dataBuf = new char[nDataLen];
if (dataBuf == NULL)
{
return -;
}
memset(dataBuf, , sizeof(dataBuf)); //assert(dataBuf != NULL); sprintf(strPos, "%d", pos); if (createDataLink(data_fd) < )
{
trace("@@@@ Create Data Link error!!!\n");
return -;
} std::string strCmdLine = parseCommand(FTP_COMMAND_DOWNLOAD_POS, strPos);//param 1 为REST命令
if (Send(m_cmdSocket, strCmdLine) < )
{
return -;
}
trace("@@@@Response: %s\n", serverResponse(m_cmdSocket).c_str()); strCmdLine = parseCommand(FTP_COMMAND_DOWNLOAD_FILE, strRemoteFile);//param 1为RETR命令 if (Send(m_cmdSocket, strCmdLine) < )
{
return -;
} std::string strResponse = serverResponse(m_cmdSocket);
trace("@@@@Response: %s\n", strResponse.c_str()); file = createLocalFile2(std::string(strLocalFile));
assert(file != NULL); int len = ;
int nReceiveLen = ;
while ((len = getData(data_fd, dataBuf, nDataLen)) > )
{
nReceiveLen += len; int num = fwrite(dataBuf, , len, file);
memset(dataBuf, , sizeof(dataBuf)); trace("Num:%d, nReceiveLen:%d\n", num, nReceiveLen); } Close(data_fd);
fclose(file);
delete[]dataBuf; return nReceiveLen; }

references:

http://blog.chinaunix.net/uid-7377299-id-112977.html