如何将文件读入std::string
,即一次读取整个文件?
调用者应指定文本或二进制模式。该解决方案应符合标准、可移植且高效。它不应该不必要地复制字符串的数据,并且应该避免在读取字符串时重新分配内存。
一种方法是统计文件大小,将 std::string
和 fread()
调整为 std::string
的 const_cast<char*>()
'ed data()
。这要求 std::string
的数据是连续的,这不是标准所要求的,但似乎所有已知实现都是如此。更糟糕的是,如果以文本模式读取文件,std::string
的大小可能不等于文件的大小。
可以使用 std::ifstream
的 rdbuf()
到 std::ostringstream
并从那里到 std::string
构建完全正确、符合标准和可移植的解决方案。但是,这可能会复制字符串数据和/或不必要地重新分配内存。
所有相关的标准库实现是否足够聪明,可以避免所有不必要的开销?
还有另一种方法吗?
我是否错过了一些已经提供所需功能的隐藏 Boost 功能?
void slurp(std::string& data, bool is_binary)
一种方法是将流缓冲区刷新到单独的内存流中,然后将其转换为 std::string
(省略错误处理):
std::string slurp(std::ifstream& in) {
std::ostringstream sstr;
sstr << in.rdbuf();
return sstr.str();
}
这非常简洁。然而,正如问题中所指出的,这执行了一个冗余副本,不幸的是,基本上没有办法删除这个副本。
不幸的是,避免冗余副本的唯一真正解决方案是手动循环读取。由于 C++ 现在已经保证了连续的字符串,因此可以编写以下内容(≥C++17,包括错误处理):
auto read_file(std::string_view path) -> std::string {
constexpr auto read_size = std::size_t(4096);
auto stream = std::ifstream(path.data());
stream.exceptions(std::ios_base::badbit);
auto out = std::string();
auto buf = std::string(read_size, '\0');
while (stream.read(& buf[0], read_size)) {
out.append(buf, 0, stream.gcount());
}
out.append(buf, 0, stream.gcount());
return out;
}
最短变体:Live On Coliru
std::string str(std::istreambuf_iterator<char>{ifs}, {});
它需要标头 <iterator>
。
有一些报告称此方法比预分配字符串和使用 std::istream::read
慢。然而,在启用了优化的现代编译器上,情况似乎不再如此,尽管各种方法的相对性能似乎高度依赖于编译器。
有关类似问题,请参见 this answer。
为了您的方便,我重新发布 CTT 的解决方案:
string readFile2(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(bytes.data(), fileSize);
return string(bytes.data(), fileSize);
}
当针对 Moby Dick (1.3M) 的文本平均运行 100 次时,此解决方案的执行时间比此处提供的其他答案快约 20%。对于可移植的 C++ 解决方案来说还不错,我想看看对文件进行映射的结果;)
&bytes[0]
取消引用 nullptr
如果您有 C++17 (std::filesystem),还有这种方式(通过 std::filesystem::file_size
而不是 seekg
和 tellg
获取文件的大小):
#include <filesystem>
#include <fstream>
#include <string>
namespace fs = std::filesystem;
std::string readFile(fs::path path)
{
// Open the stream to 'lock' the file.
std::ifstream f(path, std::ios::in | std::ios::binary);
// Obtain the size of the file.
const auto sz = fs::file_size(path);
// Create a buffer.
std::string result(sz, '\0');
// Read the whole file into the buffer.
f.read(result.data(), sz);
return result;
}
注意:如果您的标准库还不完全支持 C++17,您可能需要使用 <experimental/filesystem>
和 std::experimental::filesystem
。如果它不支持 non-const std::basic_string data,您可能还需要将 result.data()
替换为 &result[0]
。
boost::filesystem
,因此如果您没有 c++17,也可以使用 boost
利用
#include <iostream>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream input("file.txt");
std::stringstream sstr;
while(input >> sstr.rdbuf());
std::cout << sstr.str() << std::endl;
}
或非常接近的东西。我没有打开 stdlib 参考来仔细检查自己。
是的,我知道我没有按要求编写 slurp
函数。
operator>>
读入 std::basic_streambuf
时,它将消耗(剩下的)输入流,因此循环是不必要的。
我没有足够的声望直接评论使用 tellg()
的回复。
请注意,tellg()
可能会在出错时返回 -1。如果您将 tellg()
的结果作为分配参数传递,您应该首先检查结果。
问题的一个例子:
...
std::streamsize size = file.tellg();
std::vector<char> buffer(size);
...
在上面的示例中,如果 tellg()
遇到错误,它将返回 -1。有符号(即 tellg()
的结果)和无符号(即 vector<char>
构造函数的 arg)之间的隐式转换将导致您的向量错误地分配 非常 大量字节。 (可能是 4294967295 字节,或 4GB。)
修改 paxos1977 的答案以解决上述问题:
string readFile2(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
if (fileSize < 0) <--- ADDED
return std::string(); <--- ADDED
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(&bytes[0], fileSize);
return string(&bytes[0], fileSize);
}
tellg()
不返回大小而是返回一个标记。许多系统使用字节偏移量作为标记,但这不能保证,有些系统不保证。查看 this answer 以获取示例。
此解决方案将错误检查添加到基于 rdbuf() 的方法中。
std::string file_to_string(const std::string& file_name)
{
std::ifstream file_stream{file_name};
if (file_stream.fail())
{
// Error opening file.
}
std::ostringstream str_stream{};
file_stream >> str_stream.rdbuf(); // NOT str_stream << file_stream.rdbuf()
if (file_stream.fail() && !file_stream.eof())
{
// Error reading file.
}
return str_stream.str();
}
我添加这个答案是因为在原始方法中添加错误检查并不像您期望的那么简单。原始方法使用 stringstream 的插入运算符 (str_stream << file_stream.rdbuf()
)。问题是这会在没有插入字符时设置字符串流的故障位。这可能是由于错误,也可能是由于文件为空。如果您通过检查故障位来检查故障,则在读取空文件时会遇到误报。您如何区分由于文件为空而无法插入任何字符的合法失败和插入任何字符的“失败”?
您可能会考虑显式检查空文件,但这需要更多代码和相关的错误检查。
检查失败条件 str_stream.fail() && !str_stream.eof()
不起作用,因为插入操作没有设置 eofbit(在 ostringstream 或 ifstream 上)。
所以,解决办法是改变操作。不要使用 ostringstream 的插入运算符 (<<),而是使用 ifstream 的提取运算符 (>>),它确实设置了 eofbit。然后检查失败条件 file_stream.fail() && !file_stream.eof()
。
重要的是,当 file_stream >> str_stream.rdbuf()
遇到合法失败时,它不应该设置 eofbit(根据我对规范的理解)。这意味着上述检查足以检测合法故障。
这是一个使用新文件系统库的版本,具有相当强大的错误检查功能:
#include <cstdint>
#include <exception>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>
namespace fs = std::filesystem;
std::string loadFile(const char *const name);
std::string loadFile(const std::string &name);
std::string loadFile(const char *const name) {
fs::path filepath(fs::absolute(fs::path(name)));
std::uintmax_t fsize;
if (fs::exists(filepath)) {
fsize = fs::file_size(filepath);
} else {
throw(std::invalid_argument("File not found: " + filepath.string()));
}
std::ifstream infile;
infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
infile.open(filepath.c_str(), std::ios::in | std::ifstream::binary);
} catch (...) {
std::throw_with_nested(std::runtime_error("Can't open input file " + filepath.string()));
}
std::string fileStr;
try {
fileStr.resize(fsize);
} catch (...) {
std::stringstream err;
err << "Can't resize to " << fsize << " bytes";
std::throw_with_nested(std::runtime_error(err.str()));
}
infile.read(fileStr.data(), fsize);
infile.close();
return fileStr;
}
std::string loadFile(const std::string &name) { return loadFile(name.c_str()); };
infile.open
也可以接受 std::string
而无需使用 .c_str()
进行转换
filepath
不是 std::string
,而是 std::filesystem::path
。原来 std::ifstream::open
也可以接受其中之一。
std::filesystem::path
可隐式转换为 std::string
std::ifstream
上接受 std::filesystem::path
的 ::open
成员函数的运行就像在路径上调用 ::c_str()
方法一样。在 POSIX 下,路径的底层 ::value_type
是 char
。
由于这似乎是一个广泛使用的实用程序,我的方法是搜索并更喜欢已经可用的库而不是手工制作的解决方案,特别是如果您的项目中已经链接了 boost 库(链接器标志 -lboost_system -lboost_filesystem)。 Here (and older boost versions too),boost 提供了一个 load_string_file 实用程序:
#include <iostream>
#include <string>
#include <boost/filesystem/string_file.hpp>
int main() {
std::string result;
boost::filesystem::load_string_file("aFileName.xyz", result);
std::cout << result.size() << std::endl;
}
作为一个优势,这个函数不会寻找整个文件来确定大小,而是在内部使用 stat() 。不过,作为一个可能可以忽略不计的缺点,人们可以通过检查源代码轻松推断:字符串被不必要地调整为 '\0'
字符,这些字符被文件内容重写。
这样的事情应该不会太糟糕:
void slurp(std::string& data, const std::string& filename, bool is_binary)
{
std::ios_base::openmode openmode = ios::ate | ios::in;
if (is_binary)
openmode |= ios::binary;
ifstream file(filename.c_str(), openmode);
data.clear();
data.reserve(file.tellg());
file.seekg(0, ios::beg);
data.append(istreambuf_iterator<char>(file.rdbuf()),
istreambuf_iterator<char>());
}
这里的优点是我们先做保留,这样我们就不必在读入内容时增加字符串。缺点是我们逐个字符地进行。更智能的版本可以抓取整个读取缓冲区,然后调用下溢。
您可以使用“std::getline”函数,并指定“eof”作为分隔符。生成的代码虽然有点模糊:
std::string data;
std::ifstream in( "test.txt" );
std::getline( in, data, std::string::traits_type::to_char_type(
std::string::traits_type::eof() ) );
从几个地方提取信息......这应该是最快和最好的方法:
#include <filesystem>
#include <fstream>
#include <string>
//Returns true if successful.
bool readInFile(std::string pathString)
{
//Make sure the file exists and is an actual file.
if (!std::filesystem::is_regular_file(pathString))
{
return false;
}
//Convert relative path to absolute path.
pathString = std::filesystem::weakly_canonical(pathString);
//Open the file for reading (binary is fastest).
std::wifstream in(pathString, std::ios::binary);
//Make sure the file opened.
if (!in)
{
return false;
}
//Wide string to store the file's contents.
std::wstring fileContents;
//Jump to the end of the file to determine the file size.
in.seekg(0, std::ios::end);
//Resize the wide string to be able to fit the entire file (Note: Do not use reserve()!).
fileContents.resize(in.tellg());
//Go back to the beginning of the file to start reading.
in.seekg(0, std::ios::beg);
//Read the entire file's contents into the wide string.
in.read(fileContents.data(), fileContents.size());
//Close the file.
in.close();
//Do whatever you want with the file contents.
std::wcout << fileContents << L" " << fileContents.size();
return true;
}
这会将宽字符读入 std::wstring
,但如果您只需要常规字符和 std::string
,您可以轻松适应。
永远不要写入 std::string 的 const char * 缓冲区。永远不能!这样做是一个巨大的错误。
为 std::string 中的整个字符串保留()空间,从文件中读取合理大小的块到缓冲区中,然后 append()它。块的大小取决于您的输入文件大小。我很确定所有其他可移植和符合 STL 的机制都会做同样的事情(但可能看起来更漂亮)。
std::string
缓冲区是可以的;我相信它在之前的所有实际实现中都能正常工作
std::string::data()
方法可以直接修改字符串缓冲区,而无需借助 &str[0]
之类的技巧。
#include <string>
#include <sstream>
using namespace std;
string GetStreamAsString(const istream& in)
{
stringstream out;
out << in.rdbuf();
return out.str();
}
string GetFileAsString(static string& filePath)
{
ifstream stream;
try
{
// Set to throw on failure
stream.exceptions(fstream::failbit | fstream::badbit);
stream.open(filePath);
}
catch (system_error& error)
{
cerr << "Failed to open '" << filePath << "'\n" << error.code().message() << endl;
return "Open fail";
}
return GetStreamAsString(stream);
}
用法:
const string logAsString = GetFileAsString(logFilePath);
基于 CTT 解决方案的更新功能:
#include <string>
#include <fstream>
#include <limits>
#include <string_view>
std::string readfile(const std::string_view path, bool binaryMode = true)
{
std::ios::openmode openmode = std::ios::in;
if(binaryMode)
{
openmode |= std::ios::binary;
}
std::ifstream ifs(path.data(), openmode);
ifs.ignore(std::numeric_limits<std::streamsize>::max());
std::string data(ifs.gcount(), 0);
ifs.seekg(0);
ifs.read(data.data(), data.size());
return data;
}
有两个重要的区别:
tellg()
不保证返回自文件开头以来的偏移量(以字节为单位)。相反,正如 Puzomor Croatia 所指出的,它更像是一个可以在 fstream 调用中使用的令牌。 gcount()
但是确实返回上次提取的未格式化字节的数量。因此,我们打开文件,使用 ignore()
提取并丢弃其所有内容以获取文件的大小,并基于此构造输出字符串。
其次,我们避免了通过直接写入字符串来将文件数据从 std::vector<char>
复制到 std::string
。
就性能而言,这应该是绝对最快的,提前分配适当大小的字符串并调用 read()
一次。有趣的是,在 gcc 上使用 ignore()
和 countg()
代替 ate
和 tellg()
会一点一点地编译为 almost the same thing。
ifs.seekg(0)
而不是 ifs.clear()
(然后它可以工作)。
std::string::data()
在 C++17 之前返回 const char*。
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
main(){
fstream file;
//Open a file
file.open("test.txt");
string copy,temp;
//While loop to store whole document in copy string
//Temp reads a complete line
//Loop stops until temp reads the last line of document
while(getline(file,temp)){
//add new line text in copy
copy+=temp;
//adds a new line
copy+="\n";
}
//Display whole document
cout<<copy;
//close the document
file.close();
}
这是我使用的函数,在处理大文件(1GB+)时,由于某种原因,当你知道文件大小时,std::ifstream::read() 比 std::ifstream::rdbuf() 快得多,所以整个“首先检查文件大小”实际上是速度优化
#include <string>
#include <fstream>
#include <sstream>
std::string file_get_contents(const std::string &$filename)
{
std::ifstream file($filename, std::ifstream::binary);
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
file.seekg(0, std::istream::end);
const std::streampos ssize = file.tellg();
if (ssize < 0)
{
// can't get size for some reason, fallback to slower "just read everything"
// because i dont trust that we could seek back/fourth in the original stream,
// im creating a new stream.
std::ifstream file($filename, std::ifstream::binary);
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
std::ostringstream ss;
ss << file.rdbuf();
return ss.str();
}
file.seekg(0, std::istream::beg);
std::string result(size_t(ssize), 0);
file.read(&result[0], std::streamsize(ssize));
return result;
}
std::string result(size_t(ssize), 0);
用 char 0(null 或 \0)填充字符串,根据 OP 的问题,这可能被认为是“不必要的开销”
对于性能,我没有发现比下面的代码更快的东西。
std::string readAllText(std::string const &path)
{
assert(path.c_str() != NULL);
FILE *stream = fopen(path.c_str(), "r");
assert(stream != NULL);
fseek(stream, 0, SEEK_END);
long stream_size = ftell(stream);
fseek(stream, 0, SEEK_SET);
void *buffer = malloc(stream_size);
fread(buffer, stream_size, 1, stream);
assert(ferror(stream) == 0);
fclose(stream);
std::string text((const char *)buffer, stream_size);
assert(buffer != NULL);
free((void *)buffer);
return text;
}
rb
(二进制)模式而不是 r
(文本)模式。去掉 malloc()
,你就不需要它了。您可以 resize()
一个 std::string
然后 fread()
直接进入其内存缓冲区。无需malloc()
缓冲区,然后将其复制到 std::string
。
resize()
虽然毫无意义地 0 初始化了内存。当然,仍然比完整副本快,但同样毫无意义。至于这篇文章:使用断言来检查 fopen()
的结果是直截了当的邪恶和错误。必须始终检查它,而不仅仅是在调试版本中。有了这个实现,一个简单的错字会导致未定义的行为(当然,实际上是一个段错误,但这不是重点)。
您可以使用我开发的 rst C++ 库来执行此操作:
#include "rst/files/file_utils.h"
std::filesystem::path path = ...; // Path to a file.
rst::StatusOr<std::string> content = rst::ReadFile(path);
if (content.err()) {
// Handle error.
}
std::cout << *content << ", " << content->size() << std::endl;
我知道这是一个非常古老的问题,有很多答案,但没有一个提到我认为最明显的方法。是的,我知道这是 C++,使用 libc 是邪恶的和错误的或其他什么,但对此很疯狂。使用 libc 很好,尤其是对于这样一个简单的事情。
本质上:只需打开文件,获取它的大小(不一定按那个顺序),然后阅读它。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/stat.h>
static constexpr char const filename[] = "foo.bar";
int main(void)
{
FILE *fp = ::fopen(filename, "rb");
if (!fp) {
::perror("fopen");
::exit(1);
}
struct stat st;
if (::fstat(fileno(fp), &st) == (-1)) {
::perror("fstat");
::exit(1);
}
// You could simply allocate a buffer here and use std::string_view, or
// even allocate a buffer and copy it to a std::string. Creating a
// std::string and setting its size is simplest, but will pointlessly
// initialize the buffer to 0. You can't win sometimes.
std::string str;
str.reserve(st.st_size + 1U);
str.resize(st.st_size);
::fread(str.data(), 1, st.st_size, fp);
str[st.st_size] = '\0';
::fclose(fp);
}
除了(在实践中)完全可移植之外,这似乎并不比其他一些解决方案更糟糕。当然,也可以抛出异常而不是立即退出。调整 std::string
的大小总是 0 初始化它,这让我非常恼火,但它无济于事。
请注意,这只适用于为 C++17 及更高版本编写的代码。早期版本(应该)不允许编辑 std::string::data()
。如果使用早期版本,请考虑使用 std::string_view
或简单地复制原始缓冲区。
std::string
。更新。
#include <string>
#include <fstream>
int main()
{
std::string fileLocation = "C:\\Users\\User\\Desktop\\file.txt";
std::ifstream file(fileLocation, std::ios::in | std::ios::binary);
std::string data;
if(file.is_open())
{
std::getline(file, data, '\0');
file.close();
}
}
std::string get(std::string_view const& fn)
{
struct filebuf: std::filebuf
{
using std::filebuf::egptr;
using std::filebuf::gptr;
using std::filebuf::gbump;
using std::filebuf::underflow;
};
std::string r;
if (filebuf fb; fb.open(fn.data(), std::ios::binary | std::ios::in))
{
r.reserve(fb.pubseekoff({}, std::ios::end));
fb.pubseekpos({});
while (filebuf::traits_type::eof() != fb.underflow())
{
auto const gptr(fb.gptr());
auto const sz(fb.egptr() - gptr);
fb.gbump(sz);
r.append(gptr, sz);
}
}
return r;
}
我知道我迟到了,但现在(2021 年)在我的机器上,这是我测试过的最快的实现:
#include <fstream>
#include <string>
bool fileRead( std::string &contents, const std::string &path ) {
contents.clear();
if( path.empty()) {
return false;
}
std::ifstream stream( path );
if( !stream ) {
return false;
}
stream >> contents;
return true;
}
string
。即需要两倍于其他一些选项的内存。 (没有办法移动缓冲区)。对于一个大文件,这将是一个重大的惩罚,甚至可能导致分配失败。