站内搜索

下载并保存相关网页

作者: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"); //下载提示文件的默认网址

  • 上一篇:用VC6编写注册表管理程序
  • 下一篇:网络通信开发包说明与开发手册