繁体   English   中英

如何将整个文件读入 C++ 中的 std::string?

[英]How do I read an entire file into a std::string in C++?

如何将文件读入std::string ,即一次读取整个文件?

文本或二进制模式应由调用者指定。 该解决方案应符合标准、可移植且高效。 它不应不必要地复制字符串的数据,并且应避免在读取字符串时重新分配 memory。

一种方法是统计文件大小,将std::stringfread()调整为std::stringconst_cast<char*>() ed data() 这要求std::string的数据是连续的,这不是标准所要求的,但对于所有已知的实现来说似乎都是如此。 更糟糕的是,如果以文本模式读取文件,则std::string的大小可能不等于文件的大小。

可以使用std::ifstreamrdbuf()std::ostringstream并从那里到std::string来构建一个完全正确、符合标准和可移植的解决方案。 但是,这可能会复制字符串数据和/或不必要地重新分配 memory。

  • 是否所有相关的标准库实现都足够聪明,可以避免所有不必要的开销?
  • 还有另一种方法吗?
  • 我是否错过了一些已经提供所需功能的隐藏 Boost function?


void slurp(std::string& data, bool is_binary)

一种方法是将流缓冲区刷新到单独的内存流中,然后将其转换为std::string<\/code> (省略错误处理):

std::string slurp(std::ifstream& in) {
    std::ostringstream sstr;
    sstr << in.rdbuf();
    return sstr.str();
}

最短的变种: Live On Coliru<\/a><\/kbd><\/strong>

std::string str(std::istreambuf_iterator<char>{ifs}, {});

有关类似问题,请参阅此答案<\/a>。

为了您的方便,我重新发布 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);
}

如果你有 C++17(std::filesystem),也有这种方式(通过std::filesystem::file_size<\/code>而不是seekg<\/code>和tellg<\/code>获取文件的大小):

#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;
}

利用

#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;
}

我没有足够的声誉直接评论使用tellg()<\/code>的回复。

请注意, tellg()<\/code>可以在错误时返回 -1。 如果您将tellg()<\/code>的结果作为分配参数传递,您应该首先检查结果。

问题的一个例子:

...
std::streamsize size = file.tellg();
std::vector<char> buffer(size);
...

此解决方案将错误检查添加到基于 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();
}

这是一个使用新文件系统库的版本,具有相当强大的错误检查功能:

#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()); };

由于这似乎是一个广泛使用的实用程序,我的方法是搜索并更喜欢已经可用的库而不是手工制作的解决方案,特别是如果您的项目中已经链接了 boost 库(链接器标志 -lboost_system -lboost_filesystem)。 在这里(以及旧的 bo​​ost 版本)<\/a> ,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;
}

这样的事情应该不会太糟糕:

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 ,则可以轻松进行调整。

#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;
}
#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()快得多<\/em>,所以整个“首先检查文件大小”实际上是速度优化

#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;
}

我知道这是一个非常古老的问题,有很多答案,但没有一个提到我认为最明显的方法。 是的,我知道这是 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 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;
}

您可以使用我开发的第一个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;
#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 的 const char * 缓冲区。 永远不能! 这样做是一个巨大的错误。

为 std::string 中的整个字符串保留()空间,从文件中读取合理大小的块到缓冲区中,然后 append()它。 块的大小取决于您的输入文件大小。 我很确定所有其他可移植和符合 STL 的机制都会做同样的事情(但可能看起来更漂亮)。

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM