C++ 读取缓冲区中的整个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18816126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ read the whole file in buffer
提问by vard
What is a good approach to read the whole file content in a buffer for C++?
在 C++ 的缓冲区中读取整个文件内容的好方法是什么?
While in plain C I could use fopen(), fseek(), fread()
function combination and read the whole file to a buffer, is it still a good idea to use the same for C++? If yes, then how could I use RAII approach while opening, allocating memory for buffer, reading and reading file content to buffer.
虽然在普通 CI 中可以使用fopen(), fseek(), fread()
函数组合并将整个文件读取到缓冲区,但对 C++ 使用相同的方法仍然是一个好主意吗?如果是,那么我如何在打开时使用 RAII 方法,为缓冲区分配内存,读取和读取文件内容到缓冲区。
Should I create some wrapper class for the buffer, which deallocates memory (allocated for buffer) in it's destructor, and the same wrapper for file handling?
我应该为缓冲区创建一些包装类,它在其析构函数中释放内存(为缓冲区分配),以及用于文件处理的相同包装吗?
回答by jrok
There's no need for wrapper classes for very basic functionality:
非常基本的功能不需要包装类:
std::ifstream file("myfile", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
/* worked! */
}
回答by AngelCastillo
You can access the contents of a file with a input file stream std::ifstream, then you can use std::istreambuf_iteratorto iterate over the contents of the ifstream,
您可以使用输入文件流std::ifstream访问文件的内容,然后您可以使用std::istreambuf_iterator迭代 ifstream 的内容,
std::string
getFileContent(const std::string& path)
{
std::ifstream file(path);
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return content;
}
In this case im using the iterator to build a new string using the contents of the ifstream, the std::istreambuf_iterator<char>(file)
creates an iterator to the begining of the ifstream, and std::istreambuf_iterator<char>()
is a default-constructed iterator that indicate the special state "end-of-stream"which you will get when the first iterator reach the end of the contents.
在使用迭代来构建使用ifstream的内容的新的字符串此时的IM中,std::istreambuf_iterator<char>(file)
创建一个迭代器ifstream的的开头,并且std::istreambuf_iterator<char>()
是一个默认构造的迭代器指示的特殊状态“结束流”,其您将在第一个迭代器到达内容末尾时获得。
回答by ArtemGr
Something I have in most of my programs:
我在大多数程序中都有一些东西:
/** Read file into string. */
inline std::string slurp (const std::string& path) {
std::ostringstream buf;
std::ifstream input (path.c_str());
buf << input.rdbuf();
return buf.str();
}
Can be placed in a header.
I think I have found it here: https://stackoverflow.com/a/116220/257568
可以放在标题中。
我想我在这里找到了:https: //stackoverflow.com/a/116220/257568