在C++缓冲区中读取整个文件内容的好方法是什么?
虽然在普通CI中可以使用fopen(), fseek(), fread()函数组合并将整个文件读取到缓冲区,但对C++使用它仍然是个好主意吗?如果是,那么我怎样才能在打开时使用RAII方法,为缓冲区分配内存,读取和读取文件内容到缓冲区.
我应该为缓冲区创建一些包装类,它在它的析构函数中释放内存(分配给缓冲区),以及用于文件处理的相同包装器吗?
jro*_*rok 57
对于非常基本的功能,不需要包装类:
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! */
}
Run Code Online (Sandbox Code Playgroud)
Ang*_*llo 16
您可以使用输入文件流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;
}
Run Code Online (Sandbox Code Playgroud)
在使用迭代来构建使用ifstream的内容的新的字符串此时的IM中,std::istreambuf_iterator<char>(file)创建一个迭代器ifstream的的开头,并且std::istreambuf_iterator<char>()是一个默认构造的迭代器指示的特殊状态"结束流",其当第一个迭代器到达内容的末尾时,您将获得.
Art*_*mGr 13
我在大多数程序中都有的东西:
/** 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();
}
Run Code Online (Sandbox Code Playgroud)
可以放在标题中.
我想我在这里找到了它:https://stackoverflow.com/a/116220/257568
| 归档时间: |
|
| 查看次数: |
71466 次 |
| 最近记录: |