curl使用ftp获取服务器上指定目录的所有文件集合以及下载

直接编译可用,注意修改测试main函数内的字符串,注释我觉得写的挺详细了,跑不起来的评论区可问

头文件

#ifndef FTP_DOWNLOAD_H
#define FTP_DOWNLOAD_H
#include <iostream>
#include <functional>
#include <memory>
#include <vector>
#include<cstdlib>
#include <ctime>
using namespace std;
using OutPutList = vector<string>;
#define FTPBODY "ftp-list"struct FtpFile
{string local;FILE *stream;
};class FtpDownloadder
{
public:/*** @brief Construct a new Ftp Downloadder object* * @param ip * @param port * @param username * @param password */FtpDownloadder(const char *ip,const char *port,const char *username,const char *password);~FtpDownloadder();/*** @brief 获取指定文件夹下所有文件名* * @param folderName 指定文件夹名称*     (从登录用户家目录开始算,for example: /home/user/targetFolder  , you can give a param with "targetFolder")* @return OutPutList 该文件夹下的所有文件名集合,包含拓展名*/OutPutList getAllItem(const string& folderName);/*** @brief  更新本地缓存* * @param fileList ftp服务器上的文件集合* @param remotFolderPath ftp服务器上的文件夹路径*     (从登录用户家目录开始算,for example: /home/user/targetFolder  , you can give a param with "targetFolder")* @param localCacheFolder 本地缓存文件夹* @return true successful* @return false faild*/bool flashLocalCache(const OutPutList& fileList, const string& remotFolderPath, const string& localCacheFolder);/*** @brief 下载文件* * @param filePath ftp服务器上的文件路径*     (从登录用户家目录开始算,for example: /home/user/targetFolder/test.tgz  , you can give a param with "targetFolder/test.tgz")* @param localFolderPath 本地存储的文件夹全路径,默认当前程序文件夹* @return string 本地存储完整路径 */string downLoadFile(const string& filePath,const string& localFolderPath = "/home/root/test");
private:string m_url;string m_username;string m_password;};std::shared_ptr<FtpDownloadder> createFtpPtr(const char *ip,const char *port,const char *username,const char *password);#endif

cpp

#include "download.hpp"
#include <stdio.h>
#include <iostream>
#include <curl/curl.h>
#include <fstream>
#include <string.h>
#include <vector>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
using namespace std;/* <DESC>* Similar to ftpget.c but also stores the received response-lines* in a separate file using our own callback!* </DESC>*/
static size_t
write_response(void *ptr, size_t size, size_t nmemb, void *data)
{FILE *writehere = (FILE *)data;return fwrite(ptr, size, nmemb, writehere);
}
/*** @brief Get the File Name object* * @param content * @param output * @return true 是文件* @return false 不是文件*/
static bool getFileName(const string& content, char* output)
{strncpy(output,content.c_str(),1);if (strcmp(output,"d") == 0){return false;}strncpy(output,content.c_str()+56,content.length()-56);return true;
}
/*** @brief  验证文件夹是否存在,不存在则创建* * @param path * @return true * @return false */
static bool checkFolderExistAndMKDIR(const string& path)
{struct stat file_info;  if(stat(path.c_str(), &file_info) != 0)  {string tt = "mkdir -p ";tt+=path;system(tt.c_str());}
}
/*** @brief  文件写入本地* * @param buffer * @param size * @param nmemb * @param stream * @return int */
int my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{struct FtpFile *out=(struct FtpFile *)stream;if(out && !out->stream){    /* open file for writing */ out->stream=fopen((out->local).c_str(), "ab+");if(!out->stream){cout << "failure, can't open "+out->local+" to write"<<endl;return -1; /* failure, can't open file to write */ }}return fwrite(buffer, size, nmemb, out->stream);
}FtpDownloadder::FtpDownloadder(const char *ip,const char *port,const char *username,const char *password)
{m_url = "ftp://"+string(ip)+":"+string(port);m_username = username;m_password = password;
};
FtpDownloadder::~FtpDownloadder(){};OutPutList FtpDownloadder::getAllItem(const string& folderName)
{OutPutList outPutList;// TODOCURL *curl;CURLcode res;FILE *ftpfile;/* local file name to store the file as */ftpfile = fopen(FTPBODY, "wb"); /* b is binary, needed on win32 */curl = curl_easy_init();if(curl){/* Get a file listing from ftp server */string temp_url = m_url + "/"+folderName + "/";curl_easy_setopt(curl, CURLOPT_URL, temp_url.c_str());curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEDATA, ftpfile);res = curl_easy_perform(curl);/* Check for errors */if(res != CURLE_OK){fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));fclose(ftpfile);return outPutList;}/* always cleanup */curl_easy_cleanup(curl);}fclose(ftpfile); /* close the local file */string content;char buffer[312];ifstream infile(FTPBODY);if ( !infile){cout<<"ifstream infile(\"ftp-list\") failed"<<endl;return outPutList;}while (getline(infile,content)){       memset(buffer,0,312);auto temp_res = getFileName(content,buffer);if (!temp_res){continue;}outPutList.push_back(buffer);}infile.close();return outPutList;
}bool FtpDownloadder::flashLocalCache(const OutPutList& fileList, const string& remotFolderPath,const string& localCacheFolder)
{checkFolderExistAndMKDIR(localCacheFolder);// TODOfor(auto var : fileList){string filePath = remotFolderPath +"/"+ var;cout<<filePath<<endl;downLoadFile(filePath,localCacheFolder);}return true;
}string FtpDownloadder::downLoadFile(const string& filePath,const string& localFolderPath)
{checkFolderExistAndMKDIR(localFolderPath);string localPath = localFolderPath;string t_remotPath;char t_filename[255];// TODOCURL *curl;CURLcode res; curl_global_init(CURL_GLOBAL_DEFAULT);t_remotPath = m_url+"/"+filePath;memset(t_filename,0,255);auto index = strrchr(filePath.c_str(),'/');strcpy(t_filename,index+1);localPath+=string(t_filename);creat(localPath.c_str(),S_IRWXU);int use_resume = 0;curl_off_t local_file_len = -1 ; struct stat file_info;  if(stat(localPath.c_str(), &file_info) == 0)  {  local_file_len = file_info.st_size;   use_resume = 1;  }  struct FtpFile ftpfile={localPath, /* name to store the file as if successful */ NULL};// cout<< "ftpfile.local: "<<ftpfile.local<<endl;curl = curl_easy_init();if(curl) {curl_easy_setopt(curl, CURLOPT_URL, t_remotPath.c_str());        curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str()); curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, 0);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);res = curl_easy_perform(curl);  curl_easy_cleanup(curl);}curl_global_cleanup();return localPath;
}std::shared_ptr<FtpDownloadder> createFtpPtr(const char *ip,const char *port,const char *username,const char *password){return std::shared_ptr<FtpDownloadder>(new FtpDownloadder(ip,port,username,password));
}

main.cpp测试

#include "download.hpp"
#include <iostream>
using namespace std;int main(int argc, char** argv)
{auto dl=createFtpPtr("127.0.0.1","21","wangr","root");int SW = argc>1?*argv[1] - '0' : 0;// /home/用户名/qt_demostring remotFolderPath = "qt_demo";//   /home/用户名/somewhere/qt_demo// string remotFolderPath = "somewhere/qt_demo";switch (SW){case 0: dl->getAllItem(remotFolderPath);break;//   /home/用户名/u/48205129.png case 1: dl->downLoadFile("u/48205129.png","/home/wangr/d/");//  /home/用户名/somewhere/A/48205129.png // case 1: dl->downLoadFile("somewhere/A/48205129.png","/home/wangr/d/");break;case 2: dl->flashLocalCache(dl->getAllItem(remotFolderPath),remotFolderPath,"/home/wangr/d/");break;default:break;}   return 0;
}

ubuntu下linux:curl使用ftp获取服务器上指定目录的所有文件集合以及下载相关推荐

  1. java获取服务器上指定文件,java 读取服务器上文件

    java 读取服务器上文件 [2021-02-04 10:02:14]  简介: php去除nbsp的方法:首先创建一个PHP代码示例文件:然后通过"preg_replace("/ ...

  2. ftp服务器 文件目录,如何列出ftp服务器上的目录中的文件?

    我找到了一个能够列出ftp服务器根目录下的文件和目录的解决方案.但我也需要目录的内容.我需要修改这个方法吗? internal void ListFilesOnServer() { try { Ftp ...

  3. Linux下wget怎么样从FTP获取资源(有用户名和密码)

    Linux下wget怎么样从FTP获取链接 1.linux有网络的前提下,安装wget 命令:yum install wget 2.在linux命令行下输入 wget ftp://192.168.1. ...

  4. lamp 重启mysql_lamp常用命令 --Ubuntu下启动/重启/停止apache,mysql服务器

    lamp常用命令 --Ubuntu下启动/重启/停止apache,mysql服务器 (2011-08-19 16:20:35)转载▼标签: it 分类: LINUX Ubuntu下启动/重启/停止ap ...

  5. Ubuntu下Linux系统部署fisco时bash操作报错权限不足(permission denied) failed to run command ‘........‘

    Ubuntu下Linux系统部署fisco时bash操作报错权限不足(permission denied) failed to run command '-' 例如这里就指的是fisco-bcos这个 ...

  6. 解决ubuntu下root用户 不能ftp登陆的问题

    2019独角兽企业重金招聘Python工程师标准>>> 解决ubuntu下root用户 不能ftp登陆的问题 一般情况下,由于种种原因ftp是不让root用户远程登陆,但只要你修改以 ...

  7. wget 自己服务器上的文件,关于linux:wget可以用于获取服务器上的所有文件吗?...

    可以用来获取服务器上的所有文件.如果这是在我的网站foo.com上使用Django框架的目录结构,请假设 如果这是目录结构 /web/project1 /web/project2 /web/proje ...

  8. 获取服务器上图片的位置,怎么获取服务器上的图片地址

    怎么获取服务器上的图片地址 内容精选 换一换 通过云服务器或者外部镜像文件创建私有镜像时,如果云服务器或镜像文件所在虚拟机的网络配置是静态IP地址时,您需要修改网卡属性为DHCP,以使私有镜像发放的新 ...

  9. php浏览服务器某一文件夹内容,php删除web服务器中指定目录下的指定格式的文件...

    今天还在写VipSystem Pro的授权部分,用户授权后,生成匹配该用户的唯一的php文件集合(在一个目录下),然后进行zip下所并弹出下载. 这个临时生成的zip文件存放在我指定的一个目录.每个用 ...

最新文章

  1. GitLab设置中文
  2. 【线段树合并】解题报告:luogu P4556雨天的尾巴 (树上对点差分 + 动态开点 + 线段树合并)线段树合并模板离线/在线详解
  3. 查出引起死锁的进程和SQL语句
  4. ASP.NET 2.0应用程序安全强化纵览
  5. Spring Cloud Kubernetes 指南
  6. yolov3 数据预处理
  7. .NET Core开发日志——WCF Client
  8. linux中断处理汇编入口,Linux中断处理体系结构分析(一)
  9. linux无后缀名程序运行,linux – 如何在Ubuntu上运行无扩展(也许是ELF)文件?
  10. Visual Studio Code(VS Code)入门
  11. jmeter学习总结
  12. 这可能是程序员写的最暖的一首歌了
  13. springboot大学生实习管理系统
  14. python拦截游戏封包_TCP封包拦截类模块 API HooK封包拦截源码
  15. c#获取当前日期时间
  16. MongoDB文件服务器搭建
  17. 惊闻Google Reader将被关闭
  18. 林奕含《房思琪的初恋乐园》全文/原文
  19. Noip前的大抱佛脚----赛前任务
  20. 十大经典排序算法及比较与分析 ( 动画演示 ) ( 可视化工具 )

热门文章

  1. Java实现发电子邮件,快去给你好基友发一封邮件~
  2. K8s(Kubernetes)架构笔记
  3. 全网精华之C++11 60篇链接汇总
  4. 关于img标签中的alt和title属性作用的说明
  5. 女生嘴唇怎么画?写实厚涂的女生嘴唇绘画技巧
  6. python中and和or的区别-Python中and-or语法
  7. 云计算或成时代新拐点?从哪些点可以看出?
  8. Towards Efficient and Scale-Robust
  9. 不健康的生活终于让身体有了反应
  10. 数据分析和数据可视化网站资源