什么是读取C ++缓冲区中整个文件内容的好方法?
What is a good approach to read the whole file content in a buffer for C++?
在普通CI中,可以使用 fopen() ,fseek(),fread()函数组合并将整个文件读取到缓冲区中,对于C ++使用相同的文件还是个好主意吗?如果是,那么我如何在打开时使用RAII方法,为缓冲区分配内存,将文件内容读取和读取到缓冲区中。
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.
我应该为缓冲区创建一些包装器类,该类在其析构函数中分配内存(为缓冲区分配),以及用于文件处理的相同包装器吗?
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?
推荐答案对于非常基本的功能,不需要包装类:
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! */ }更多推荐
C ++读取缓冲区中的整个文件
发布评论