linux c++下载http文件并显示进度<转>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <fstream>
#include <vector>
#include <pthread.h>
using namespace std;
typedef string::size_type (string::*find_t)(const string& delim,
string::size_type offset) const;
vector<string> Split(const string& s,
const string& match,
bool removeEmpty=false,
bool fullMatch=false)
{
vector<string> result; // return container for tokens
string::size_type start = , // starting position for searches
skip = ; // positions to skip after a match
find_t pfind = &string::find_first_of; // search algorithm for matches
if (fullMatch)
{
skip = match.length();
pfind = &string::find;
}
while (start != string::npos)
{
string::size_type end = (s.*pfind)(match, start);
if (skip == ) end = string::npos;
string token = s.substr(start, end - start);
if (!(removeEmpty && token.empty()))
{
result.push_back(token);
}
if ((start = end) != string::npos) start += skip;
}
return result;
}
void SplitProperty(vector<string> property,string* name,string *value)
{
vector<string>::iterator it=property.begin();
if(it!= property.end())
{
name->clear();
name->append(*it);
}
it++;
if(it!= property.end())
{
value->clear();
value->append(*it);
}
}
int GetFileSize(char* host,char* file,string* error,int& headersize)
{
int size=-;
struct sockaddr_in servaddr;
struct hostent *hp;
string splitline="\r\n";
string PName;
string PValue;
string splittagbalue=":";
string info;
vector<string> properties;
vector<string> property;
int sock_id;
char message[*] = {};
int msglen;
string request;
request.append("HEAD ");
request.append(file);
request.append(" HTTP/1.1\n");
request.append("Host:");
request.append(host);
request.append("\r\n\r\n");
//Get a socket
if((sock_id = socket(AF_INET, SOCK_STREAM, )) == -) {
error->append("Couldn't get a socket!");
return size;
}
//book uses bzero which my man pages say is deprecated
//the man page said to use memset instead. :-)
memset(&servaddr,,sizeof(servaddr));
//get address for google.com
if((hp = gethostbyname(host)) == NULL) {
error->append("Couldn't access network.");
error->append(host);
return size;
}
//bcopy is deprecated also, using memcpy instead
memcpy((char *)&servaddr.sin_addr.s_addr, (char *)hp->h_addr, hp->h_length);
//fill int port number and type
servaddr.sin_port = htons();
servaddr.sin_family = AF_INET;
//make the connection
if(connect(sock_id, (struct sockaddr *)&servaddr, sizeof(servaddr)) != ) {
error->append("Couldn't connect!");
return size;
}
write(sock_id,request.c_str(),request.length());
//read the response
msglen = read(sock_id,message,*);
headersize= msglen;
info.append(message,,msglen);
close(sock_id);
properties =Split(info,splitline,true);
vector<string>::iterator it;
for (it=properties.begin(); it<properties.end(); it++)
{
property= Split(*it,splittagbalue,true);
SplitProperty(property,&PName,&PValue);
if(PName=="Content-Length")
{
size =atoi(PValue.c_str());
break;
}
}
if(size==-)
{
error->append("Resource Not Found!");
}
return size;
}
void DownloadFile(char* host,char* file,char * savefile,float size,int& progress,int hsize)
{
struct sockaddr_in servaddr;
struct hostent *hp;
string info;
int sock_id;
char message[] = {};
char messagetop[]={};
int msglen;
float readcount=;
string request;
request.append("GET ");
request.append(file);
request.append(" HTTP/1.1\n");
request.append("Host:");
request.append(host);
request.append("\r\n\r\n");
//Get a socket
if((sock_id = socket(AF_INET, SOCK_STREAM, )) == -) {
return;
}
//book uses bzero which my man pages say is deprecated
//the man page said to use memset instead. :-)
memset(&servaddr,,sizeof(servaddr));
//get address for google.com
if((hp = gethostbyname(host)) == NULL) {
return;
}
//bcopy is deprecated also, using memcpy instead
memcpy((char *)&servaddr.sin_addr.s_addr, (char *)hp->h_addr, hp->h_length);
//fill int port number and type
servaddr.sin_port = htons();
servaddr.sin_family = AF_INET;
//make the connection
if(connect(sock_id, (struct sockaddr *)&servaddr, sizeof(servaddr)) != ) {
return;
}
//NOW THE HTTP PART!!!
//send the request
write(sock_id,request.c_str(),request.length());
ofstream outfile (savefile,ofstream::binary);
do{
msglen = read(sock_id,message,);
if(msglen==)
break;
if(readcount==)
{
int tempindex=;
for(int i =hsize-;i<msglen;i++)
{
messagetop[tempindex]= message[i];
tempindex=tempindex+;
}
outfile.write (messagetop,tempindex);
}
else
{
outfile.write (message,msglen);
}
readcount=readcount+msglen;
progress=readcount/size*;
}while(readcount<=(size+ hsize));
outfile.close();
close(sock_id);
//read the response
}
float filesize;
int loadprogress=;
int hsize;
pthread_t tUpdateWork;
void* UpdateWorCoping(void* data)
{
DownloadFile("192.168.2.128","/games.data","/usr/games.data",filesize,loadprogress,hsize);
}
int main(int argc, char** argv)
{
string error;
filesize = GetFileSize("192.168.2.128","/games.data",&error,hsize);
pthread_create(&tUpdateWork,NULL,UpdateWorCoping,);
while(loadprogress<)
{
printf("Progress %d \n", loadprogress);
usleep();
}
return ;
}
在使用该代码测试的时候可能会出现的问题:
1.
在DownloadFile 内的有两处:
char message[18000] = {0}; char messagetop[18000]={0};2.
在DownloadFile() 内的写文件中:
里面有个for循环:for(int i = hsize -1; i<msglen ; i++)
我在亲自测试的发现 hsize - 1 会使文件保存大小跟原始文件有出入。于是暂时改成了 for(int i = hsize ; i<msglen ; i++)
不知道对于其他类型文件是否应该 做 -1 操作。待以后再测一测看看。
linux c++下载http文件并显示进度<转>的更多相关文章
- 实现在 .net 中使用 HttpClient 下载文件时显示进度
在 .net framework 中,要实现下载文件并显示进度的话,最简单的做法是使用 WebClient 类.订阅 DownloadProgressChanged 事件就行了. 但是很可惜,WebC ...
- 使用libcurl开源库和Duilib做的下载文件并显示进度条的小工具
转载:http://blog.csdn.net/mfcing/article/details/43603525 转载:http://blog.csdn.net/infoworld/article/de ...
- C# WinFrom 导入Excel文件,显示进度条
因为WINForm程序是在64位上运行如果使用另外一种快速的读取Excel的方法会报“未在本地计算机上注册“Microsoft.Jet.OLEDB.12.0”提供程序” 所以我就换了现在这种读取有点慢 ...
- 从Linux服务器下载网站文件
最近公司迁来一个新客户,该客户的网站是别的网络服务商做的,放在linux主机上,因为客户跟之前的网络服务商合作的不愉快 所以就把网站迁到我们公司,经理让我把网站文件和数据库download下来并在我们 ...
- C# Winform下载文件并显示进度条
private void btnDown_Click(object sender, EventArgs e) { DownloadFile("http://localhost:1928/We ...
- Winform下载文件并显示进度条
本来是要研究怎样判断下载完成,结果找到这个方法,可以在这个方法完成之后提示下载完成. 代码如下: using System; using System.Collections.Generic; usi ...
- 通过HttpUrlConnection下载文件并显示进度条
实现效果: 核心下载块: int count = 0; URL url = new URL("http://hezuo.downxunlei.com/xunlei_hezuo/thunder ...
- [c#]WebClient异步下载文件并显示进度
摘要 在项目开发中经常会用到下载文件,这里使用winform实现了一个带进度条的例子. 一个例子 using System; using System.Collections.Generic; usi ...
- ajax 上传文件,显示进度条,进度条100%,进度条隐藏,出现卡顿就隐藏进度条,显示正在加载,再显示上传完成
<form id="uploadForm" method="post" enctype="multipart/form-data"&g ...
随机推荐
- C#常用插件和工具
Code generation(代码自动生成) NVelocity CodeSmith X-Code .NET XGoF - NMatrix / DEVerest Compilation(编译工具) ...
- 如何生成SPFILE文件
1.spfile是Oracle9i之后引入的,目的是提高系统安全性.在Oracle8i下初始化参数文件为文本文件,可以使用文本编辑器进行编辑,当需要修改初始化参数时,需要在init.ora文件中修改, ...
- spring考试
- 嵌入式QT程序的汉字显示
因底层服务程序全是GBK格式的,所以QT程序要全部更改编码方式. 1.QT程序编码更改 creator->edit->更改编码方式GBK main程序中做如下修改,并注意语句次序 int ...
- 4G的添加
(ZTE 中兴 ME3760_V2 ) 1. 复制myLte文件到相关目录,设置权限为755 2.修改openwrt1407/package/base-files/files/etc/rc.local ...
- python下的类的部分特点
#coding=utf-8 class data: def __init__(self): #构造函数 self.name=' def pp(self): print self.name class ...
- Java之 Hashtable
Hashtable是Java中键值对数据结构的实现.您可以使用“键”存储和检索“值”,它是存储值的标识符.显然“关键”应该是独一无二的. java.util.Hashtable扩展Dictionary ...
- a标签不用点击模拟跳转url。
因为请求到数据前要判断用户是否是登录状态, 所以就想页面数据请求成功,就跳转到登录页面, 就用了location.href = url. 结果因为同源策略不能访问, 没想到a标签竟然可以直接跳转这个U ...
- wxWidgets:给窗口添加工具条
请先看上一篇<wxWidgets入门>. 修改MyFrame.h: #ifndef MYFRAME_H #define MYFRAME_H #include <wx/wxprec.h ...
- Logstash之一:入门介绍
简介 Logstash是一个接收,处理,转发日志的工具.支持系统日志,webserver日志,错误日志,应用日志,总之包括所有可以抛出来的日志类型.怎么样听起来挺厉害的吧?在一个典型的使用场景下(EL ...