下面的代码运行时报错为:Exception read_some End of file asiomisc2请修改代码:#include iostream#include fstream#include string#include vector#include boostasiohppusing boostasioiptcp; 下载accession号并保存到文件void downloadAcce
修改后的代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
// 下载accession号并保存到文件
void downloadAccessionNumbers(const std::string& geneName, const std::string& outputFile)
{
try {
// 创建IO上下文
boost::asio::io_context io_context;
// 解析NCBI服务器的IP地址和端口号
tcp::resolver resolver(io_context);
tcp::resolver::results_type endpoints = resolver.resolve("www.ncbi.nlm.nih.gov", "http");
// 创建socket并连接到NCBI服务器
tcp::socket socket(io_context);
boost::asio::connect(socket, endpoints);
// 发送HTTP GET请求
std::string request = "/bioproject/?term=" + geneName + "&report=docsum&format=text";
boost::asio::write(socket, boost::asio::buffer("GET " + request + " HTTP/1.1\r\n"
"Host: www.ncbi.nlm.nih.gov\r\n"
"Connection: close\r\n\r\n"));
// 读取服务器响应
std::ofstream outputFileStream(outputFile);
std::string response;
std::vector<char> responseBuffer(1024);
std::size_t bytesRead = 0;
boost::system::error_code error;
do
{
bytesRead = socket.read_some(boost::asio::buffer(responseBuffer), error);
if (error == boost::asio::error::eof)
{
break; // 到达文件末尾
}
else if (error)
{
throw boost::system::system_error(error); // 其他错误
}
// 将响应缓冲区中的数据追加到字符串
response.append(responseBuffer.data(), bytesRead);
} while (true);
// 在响应中搜索accession号,并将其写入文件
size_t found = response.find("ACCESSION ");
while (found != std::string::npos)
{
size_t end = response.find("\n", found);
std::string accession = response.substr(found + 10, end - found - 10);
outputFileStream << accession << std::endl;
found = response.find("ACCESSION ", found + 1);
}
// 关闭文件和socket
outputFileStream.close();
socket.close();
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
}
int main()
{
std::string geneName = "phoD";
std::string outputFile = "accession_numbers.txt";
downloadAccessionNumbers(geneName, outputFile);
return 0;
}
在读取服务器响应的循环中,添加了对read_some返回值的判断和错误处理。当read_some返回0时,表示已经到达文件末尾,此时跳出循环。当read_some返回其他值时,检查是否有错误发生,如果有错误则抛出异常。这样可以避免在读取响应时出现EOF错误。
原文地址: https://www.cveoy.top/t/topic/inha 著作权归作者所有。请勿转载和采集!