Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file-contents into a string in C++ [duplicate]

Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?

In scripting languages like Perl, it is possible to read a file into a variable in one shot.

    open(FILEHANDLE,$file);     $content=<FILEHANDLE>; 

What would be the most efficient way to do this in C++?

like image 259
sonofdelphi Avatar asked May 26 '10 11:05

sonofdelphi


People also ask

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.

How does Getline work in C?

The getline method reads a full line from a stream, such as a newline character. To finish the input, use the getline function to generate a stop character. The command will be completed, and this character will be removed from the input.

How does Fgets work in C?

C library function - fgets() The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.


2 Answers

Like this:

#include <fstream> #include <string>  int main(int argc, char** argv) {    std::ifstream ifs("myfile.txt");   std::string content( (std::istreambuf_iterator<char>(ifs) ),                        (std::istreambuf_iterator<char>()    ) );    return 0; } 

The statement

  std::string content( (std::istreambuf_iterator<char>(ifs) ),                        (std::istreambuf_iterator<char>()    ) ); 

can be split into

std::string content; content.assign( (std::istreambuf_iterator<char>(ifs) ),                 (std::istreambuf_iterator<char>()    ) ); 

which is useful if you want to just overwrite the value of an existing std::string variable.

like image 51
Maik Beckmann Avatar answered Sep 29 '22 22:09

Maik Beckmann


The most efficient, but not the C++ way would be:

   FILE* f = fopen(filename, "r");     // Determine file size    fseek(f, 0, SEEK_END);    size_t size = ftell(f);     char* where = new char[size];     rewind(f);    fread(where, sizeof(char), size, f);     delete[] where; 

#EDIT - 2

Just tested the std::filebuf variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.

   std::ifstream file(filename, std::ios::binary);    std::streambuf* raw_buffer = file.rdbuf();     char* block = new char[size];    raw_buffer->sgetn(block, size);    delete[] block; 

I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary and rb) modes.

[==========] Running 3 tests from 1 test case. [----------] Global test environment set-up. [----------] 4 tests from IO [ RUN      ] IO.C_Kotti [       OK ] IO.C_Kotti (78 ms) [ RUN      ] IO.CPP_Nikko [       OK ] IO.CPP_Nikko (106 ms) [ RUN      ] IO.CPP_Beckmann [       OK ] IO.CPP_Beckmann (1891 ms) [ RUN      ] IO.CPP_Neil [       OK ] IO.CPP_Neil (234 ms) [----------] 4 tests from IO (2309 ms total)  [----------] Global test environment tear-down [==========] 4 tests from 1 test case ran. (2309 ms total) [  PASSED  ] 4 tests. 
like image 37
M. Williams Avatar answered Sep 29 '22 21:09

M. Williams