下面的代码运行时报错为:Exception read End of file asiomisc2请修改代码:#include iostream#include fstream#include string#include vector#include boostasiohppusing boostasioiptcp; 下载accession号并保存到文件void downloadAccession
修改后的代码如下:
#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;
do
{
bytesRead = socket.read_some(boost::asio::buffer(responseBuffer));
// 将响应缓冲区中的数据追加到字符串
response.append(responseBuffer.data(), bytesRead);
} while (bytesRead > 0);
// 在响应中搜索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;
}
在读取服务器响应的部分,将原来的boost::asio::transfer_all()修改为socket.read_some(),并使用do-while循环读取服务器响应,直到读取完毕。这样可以避免出现"End of file"的异常。
原文地址: https://www.cveoy.top/t/topic/ing3 著作权归作者所有。请勿转载和采集!