gpt4 book ai didi

C++/CLI - URL 下载到文件

转载 作者:行者123 更新时间:2023-11-28 08:16:41 25 4
gpt4 key购买 nike

我并不完全熟悉 CLI 的工作原理,但我有一个大概的概念。我有一个函数需要 2 个 System::String 变量,并使用它们从网页下载文件。就下载而言,它工作正常,文件显示在我的目录中,包含必要的内容。但是,它给了我错误

An unhandled exception of type 'System.AccessViolationException' occurred in 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";

全新错误! :(

An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in ParseLinks.exe

文件后的代码->线数组循环

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;
}

错误指向我在这个函数中的大型比较语句。 (此外,我在压缩代码方面显然很糟糕)

最佳答案

您错误地使用了 getline,这可能导致了您的错误。正确的成语是这样的:

std::string line;
while (std::getline(myFile, line))
{
// process `line`
}

无需单独检查myFile的开放性。

关于C++/CLI - URL 下载到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com