Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ read the whole file in buffer [duplicate]

Tags:

c++

raii

What is a good approach to read the whole file content in a buffer for 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.

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?

like image 670
vard Avatar asked Sep 15 '13 18:09

vard


People also ask

Does fread read whole files?

Return Value. The fread() function returns the number of full items successfully read, which can be less than count if an error occurs, or if the end-of-file is met before reaching count.

Can you read a file twice in C?

You can use fseek() to go back to the beginning of the file and read it again. You need to close the file or call fflush() after adding to the file, to flush the output buffer.


2 Answers

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! */ } 
like image 65
jrok Avatar answered Sep 22 '22 18:09

jrok


You can access the contents of a file with a input file stream std::ifstream, then you can use std::istreambuf_iterator to iterate over the contents of the 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.

like image 44
AngelCastillo Avatar answered Sep 23 '22 18:09

AngelCastillo