程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> VC >> VC++ >> 下載並保存相關網頁

下載並保存相關網頁

編輯:VC++

作者:Future Studio.徐景周
版權所有:徐景周
轉載請聯系作者

基本構成思想:利用WinInet類,直接打開會話,進行讀取並保存網頁來相關文件中。

實現涵數如下:

BOOL GetSourceHtml(CString theUrl,CString Filename)
{
CInternetSession session;
CInternetFile* file = NULL;
try
{
// 試著連接到指定URL
file = (CInternetFile*) session.OpenURL(theUrl);
}
catch (CInternetException* m_pException)
{
// 如果有錯誤的話,置文件為空
file = NULL;
m_pException->Delete();
return FALSE;
}

// 用dataStore來保存讀取的網頁文件
CStdioFile dataStore;

if (file)
{
CString somecode; //也可采用LPTSTR類型,將不會刪除文本中的\n回車符

BOOL bIsOk = dataStore.Open(strPath+"\\"+Filename,
CFile::modeCreate
| CFile::modeWrite
| CFile::shareDenyWrite
| CFile::typeText);

if (!bIsOk)
return FALSE;

// 讀寫網頁文件,直到為空
while (file->ReadString(somecode) != NULL) //如果采用LPTSTR類型,讀取最大個數nMax置0,使它遇空字符時結束
{
dataStore.WriteString(somecode);
dataStore.WriteString("\n"); //如果somecode采用LPTSTR類型,可不用此句
}

file->Close();
delete file;
}
else
{
dataStore.WriteString(_T("到指定服務器的連接建立失敗..."));
return FALSE;
}

return TRUE;
}


下面讓我們來看看,如何使用它:

1、 加入WinInt類,如下:

#include "afxinet.h" //加入下載網頁要用的頭文件


2、 加入上面下載涵數到你的工程後,在使用時可用下面代碼(其中第一個參數為網址,第二個參數為下載後保存的文件名):

//獲取主程序所在路徑,存在全局變量strPath中
GetModuleFileName(NULL,strPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
strPath.ReleaseBuffer ();
int nPos;
nPos=strPath.ReverseFind ('\\');
strPath=strPath.Left (nPos);

BOOL m_bDownloadFailed; m_bDownloadFailed=GetSourceHtml("http://www.vckbase.com","News.txt"); //下載提示文件的默認網址

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved