【发布时间】:2011-09-23 00:26:41
【问题描述】:
我并不完全熟悉 CLI 的工作原理,但我有一个大致的想法。我有一个函数,它需要 2 个 System::String 变量,并使用这些变量从网页下载文件。就下载而言,它运行良好,并且该文件显示在我的目录中,其中包含必要的内容。但是,它给了我错误
“System.AccessViolationException”类型的未处理异常 发生在 ParseLinks.exe 中
void downloadFile(System::String ^_URL, System::String ^_saveAs)
{
try
{
System::Net::WebClient ^webClient = gcnew System::Net::WebClient();
// Downloads the resource with the specified URI to a local file.
webClient->DownloadFile(_URL, _saveAs);
webClient->Dispose();
}
catch (System::Exception ^_e)
{
// Error
System::Console::WriteLine("Exception caught in process: {0}", _e);
}
}
我做了一些挖掘和输出测试,发现exe在文本文件的某个地方遇到了断点,因为整个网页没有保存到txt文件中。
相关代码:
if (myFile.is_open()) //if file open
{
while (!myFile.eof()) //before end of file
{
getline(myFile, ln);
lines[count] = ln;
count++; //count total lines to set loop length for later parsing
//Error occurs somewhere in here
}
myFile.close();
}
else
cout<<"Error: Could not access file\n";
全新错误! :(
ParseLinks.exe 中出现“System.Runtime.InteropServices.SEHException”类型的未处理异常
文件后面的代码->线数组循环
myFile.close(); //Close txt file
//Loop through lines
for (int i = 0; i < count; i++)
{
string temp = parseLinks(lines[i]); //parse links from each line
功能:
string parseLinks(string str)
{
const int len = str.length();
string link;
bool quotes = false, islink = false;
string compare[5] = {".htm",".html",".php",".asp",".pdf"};
//Parse all quoted text
for (int i = 0; i != len; i++)
{
//Change bool if quote found
if (str[i] == '"')
{
if (quotes == false)
quotes = true;
else
quotes = false;
}
//If bool true, and char is not a quote, add to link string
if (quotes == true && str[i] != '"')
link += str[i];
}
//Discard non-link text
for (int i = 0; i < 5; i++)
{
//Link check for links given array of path filetypes
if (link.compare((link.length() - compare[i].length()),compare[i].length(),compare[i]) == 0)
islink = true;
}
//Link check for links with no path filetype (.html, .php, etc.)
if (link.compare(0,7,"http://") == 0)
islink = true;
//If not a link, return empty string
if (islink == false)
link = "";
return link;
}
错误指向我在这个函数中的大比较语句。 (另外,我在压缩代码方面显然很糟糕)
【问题讨论】:
-
什么是
lines,它是如何初始化的? -
这是我用于每一行文本的数组。我从文件中取出每一行文本,将其填充到一个数组中(出于循环目的),然后将每一行拍摄到一个函数以确定它是否包含链接。对于找到的每个链接,它将其射入第二个链接数组。 (它忽略重复和外部网站)对于链接数组中的每个链接,它重新执行整个过程,转到那个网站,下载页面,解析链接,并将它们添加到数组中。它基本上是一个粗糙的网站爬虫。另外,哎呀:我只将两个数组都初始化为 100 个元素,谢谢!
-
没有全部保存不意味着错误在保存过程的中途。很有可能,但系统通常会缓冲文件写入,并且访问冲突(如果它导致程序终止)会使“写入”(但实际上只是缓冲)数据消失得无影无踪。
-
我最终找出了第二个错误。它与尝试将找到的链接与另一个具有一定长度的变量进行比较有关,当找到的链接至少没有它试图与之比较的变量一样长时。
标签: c++ url download c++-cli command-line-interface