Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to read a text file with c++?

Tags:

c++

text

file-io

I'd like to read whole content of a text file to a std::string object with c++.

With Python, I can write:

text = open("text.txt", "rt").read() 

It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++? Thanks.

like image 696
Fang-Pen Lin Avatar asked Oct 12 '08 10:10

Fang-Pen Lin


People also ask

How do you read each line in a file C?

The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be.


2 Answers

There are many ways, you pick which is the most elegant for you.

Reading into char*:

ifstream file ("file.txt", ios::in|ios::binary|ios::ate); if (file.is_open()) {     file.seekg(0, ios::end);     size = file.tellg();     char *contents = new char [size];     file.seekg (0, ios::beg);     file.read (contents, size);     file.close();     //... do something with it     delete [] contents; } 

Into std::string:

std::ifstream in("file.txt"); std::string contents((std::istreambuf_iterator<char>(in)),      std::istreambuf_iterator<char>()); 

Into vector<char>:

std::ifstream in("file.txt"); std::vector<char> contents((std::istreambuf_iterator<char>(in)),     std::istreambuf_iterator<char>()); 

Into string, using stringstream:

std::ifstream in("file.txt"); std::stringstream buffer; buffer << in.rdbuf(); std::string contents(buffer.str()); 

file.txt is just an example, everything works fine for binary files as well, just make sure you use ios::binary in ifstream constructor.

like image 145
Milan Babuškov Avatar answered Oct 24 '22 00:10

Milan Babuškov


There's another thread on this subject.

My solutions from this thread (both one-liners):

The nice (see Milan's second solution):

string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>()); 

and the fast:

string str(static_cast<stringstream const&>(stringstream() << ifs.rdbuf()).str()); 
like image 21
Konrad Rudolph Avatar answered Oct 24 '22 00:10

Konrad Rudolph