推荐使用预分配内存或rdbuf()读取文件,第一种方法通过seekg获取大小后一次性读入,高效适用于二进制;第三种用stringstream结合rdbuf()自动管理内存,适合文本文件。

在C++中,将文件内容读取到
std::string
<fstream>
<string>
这种方法简洁高效,适合大多数情况。通过获取文件大小并一次性读入字符串:
#include <iostream>
#include <fstream>
#include <string>
std::string readFileToString(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file) {
throw std::runtime_error("无法打开文件: " + filename);
}
// 获取文件大小
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
// 分配字符串空间并读取数据
std::string content(size, '\0');
file.read(&content[0], size);
if (!file) {
throw std::runtime_error("读取文件时出错");
}
return content;
}
优点:效率高,避免多次内存分配;注意:使用
std::ios::binary
无需手动处理文件大小,代码更简洁,但可能稍慢于第一种方法:
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <string>
#include <iterator>
std::string readFileToString(const std::string& filename) {
std::ifstream file(filename);
if (!file) {
throw std::runtime_error("无法打开文件");
}
std::string content(
(std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>()
);
return content;
}
说明:利用迭代器范围构造字符串,自动处理整个流内容,适合小到中等大小的文件。
如果需要按行处理或担心内存占用,可逐行读取:
#include <fstream>
#include <string>
#include <sstream>
std::string readFileToString(const std::string& filename) {
std::ifstream file(filename);
if (!file) {
throw std::runtime_error("无法打开文件");
}
std::stringstream buffer;
buffer << file.rdbuf(); // 将整个文件流写入stringstream
return buffer.str();
}
优势:清晰安全,
std::stringstream
基本上就这些。推荐优先使用第一种(带
seekg
rdbuf()
std::ios::binary
以上就是c++++中如何读取文件到string_C++文件内容读取至string的方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号