利用curl下载文件(进度条显示)的代码片段
来源:优易学  2011-1-4 9:46:21   【优易学:中国教育考试门户网】   资料下载   IT书店
  在项目中需要用到程序更新的功能,同事介绍说是curl中的开发库很牛x,又是跨平台(他们总是这么喜欢跨平台的东西 *_*),于是下载这个包测试了一下,确实不错。准备正式用到项目中,以下一个例子用于从互联网上抓取一个文件下载到本地,并加上进度条显示,做得挺简陋,不过功能差不多就这样了。
  程序运行预览.  

  首先需要加入多线程的机制,因为程序一边在下载文件,一边在显示进度条,单线程的方式肯定不行,所以我用到了wxTimer来实现,在downloadMain.h 中定义了一个wxTimer,并做了事件申明.
  DECLARE_EVENT_TABLE()
  #ifndef DOWNLOADMAIN_H
  #define DOWNLOADMAIN_H
  #include "downloadApp.h"
  #include <wx/timer.h>
  #include "GUIDialog.h"
  class downloadDialog: public GUIDialog
  {
  public:
  downloadDialog(wxDialog *dlg);
  ~downloadDialog();
  void OnTimer(wxTimerEvent& event);
  private:
  virtual void OnClose(wxCloseEvent& event);
  virtual void OnQuit(wxCommandEvent& event);
  virtual void OnAbout(wxCommandEvent& event);
  void downloadfile();
  wxTimer* m_timerdown;
  DECLARE_EVENT_TABLE()
  };
  #endif // DOWNLOADMAIN_H
  下面是主程序的代码.
  #ifdef WX_PRECOMP
  #include "wx_pch.h"
  #endif
  #ifdef __BORLANDC__
  #pragma hdrstop
  #endif //__BORLANDC__
  #include "downloadMain.h"
  #include <curl/curl.h>
  #include <curl/types.h>
  #include <curl/easy.h>
  #include "update.h"
  #include <wx/msgdlg.h>
  #include <wx/utils.h>
  #define TIMER_ID 22222
  //事件监听声明
  BEGIN_EVENT_TABLE(downloadDialog, GUIDialog)
  EVT_TIMER(TIMER_ID, downloadDialog::OnTimer)
  END_EVENT_TABLE()
  enum wxbuildinfoformat
  {
  short_f, long_f
  };
  wxString wxbuildinfo(wxbuildinfoformat format)
  {
  wxString wxbuild(wxVERSION_STRING);
  if (format == long_f )
  {
  #if defined(__WXMSW__)
  wxbuild << _T("-Windows");
  #elif defined(__WXMAC__)
  wxbuild << _T("-Mac");
  #elif defined(__UNIX__)
  wxbuild << _T("-Linux");
  #endif
  #if wxUSE_UNICODE
  wxbuild << _T("-Unicode build");
  #else
  wxbuild << _T("-ANSI build");
  #endif // wxUSE_UNICODE
  }
  return wxbuild;
  }
  //声明一个文件结构体
  struct FtpFile
  {
  char *filename;
  FILE *stream;
  };
  downloadDialog::downloadDialog(wxDialog *dlg)
  : GUIDialog(dlg)
  {
  //创建一个定时器,制定TIMER_ID
  m_timerdown = new wxTimer(this, TIMER_ID);
  //定时器开始运行,这里会自动执行OnTimer函数
  m_timerdown->Start(100);
  }
  downloadDialog::~downloadDialog()
  {
  }

[1] [2] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训