下面的代码输出的txt文件为空请修改代码:#include iostream#include fstream#include string#include vector#include boostasiohppusing boostasioiptcp; 下载accession号并保存到文件void downloadAccessionNumbersconst stdstring& geneName
#include
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;
}
原文地址: https://www.cveoy.top/t/topic/inhe 著作权归作者所有。请勿转载和采集!