Read whole ASCII file into C++ std::string [duplicate]
Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html)
You can make a streambuf iterator out of the file and initialize the string with it:
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
Not sure where you're getting the t.open("file.txt", "r")
syntax from. As far as I know that's not a method that std::ifstream
has. It looks like you've confused it with C's fopen
.
Edit: Also note the extra parentheses around the first argument to the string constructor. These are essential. They prevent the problem known as the "most vexing parse", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.
Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
Read file-contents into a string in C++ [duplicate]
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.
How do I read a file in C++ and write contents into a string? [duplicate]
Don't use <<
to append something in a string.
Rather than:
while (getline(shaderFile, line)) {
sourceCode << line;
}
Consider:
while (getline(shaderFile, line)) {
sourceCode += line;
}
How to read total file line by line and set value to string [duplicate]
If you need to read the whole content of a text file into a std::string
, you can use the code below.
The function ReadTextFile
uses std::ifstream ::rdbuf
to extract the content of the file into a std::stringstream
. Then it uses std::stringstream::str
to convert into a std::string
.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
bool ReadTextFile(std::string const & fileName, std::string & text)
{
std::stringstream strStream;
std::ifstream fileStream(fileName);
if (!fileStream.is_open())
{
return false;
}
strStream << fileStream.rdbuf();
fileStream.close();
text = strStream.str();
return true;
}
int main()
{
std::string text;
if (!ReadTextFile("t.txt", text))
{
std::cout << "failed" << std::endl;
return 1;
}
std::cout << text << std::endl;
return 0;
}
A side note: better to avoid using namespace std
- see here Why is "using namespace std;" considered bad practice?.
Related Topics
Fastest Way to Check If a File Exists Using Standard C++/C++11,14,17/C
Setting Timeout for C/C++ Function Call
Most Efficient Way of Copying a Raw Byte Array into an Empty Byte Vector
How to Remove "Noise" from Gcc/Clang Assembly Output
How to Tokenize a String in C++
Why Does an Overridden Function in the Derived Class Hide Other Overloads of the Base Class
C++ Delete - It Deletes My Objects But I Can Still Access the Data
How to Add Reflection to a C++ Application
If You Shouldn't Throw Exceptions in a Destructor, How to Handle Errors in It
Infinite Loop With Cin When Typing String While a Number Is Expected
What Is a "Cache-Friendly" Code
When Should I Use the New Keyword in C++
How to Execute a Functor or a Lambda in a Given Thread in Qt, Gcd-Style
What Does a Colon in a Struct Declaration Mean, Such as :1, :7, :16, or :32