I have a file which contains text. I read line by line of the entire file and append to a string object. But when i get the final string print out i am not getting the whole file content. I am sure it is due to the pres开发者_开发问答ence of special characters like '\n', '\r', '\t', etc.
here is my sample code:
// Read lines until end of file (null) is reached
do
{
line = "";
inputStream->read_line(line);
cout<<"\n "<<line;//here i get the content of each line
fileContent.append(line);// here i am appending
}while(line.compare("") != 0);
This is the way to read a file into memory in C++:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
vector <string> lines;
ifstream ifs( "myfile.txt" );
string line;
while( getline( ifs, line ) ) {
lines.push_back( line );
}
// do something with lines
}
You’ll have to show more code for me to know what your problem is.
If you’re reading the entire file into a single string, this is the method I usually use:
#include <string>
#include <fstream>
#include <iterator>
std::string read_file(const char *file_name)
{
std::filebuf fb;
if(!fb.open(file_name, std::ios_base::in))
{
// error.
}
return std::string(
std::istreambuf_iterator<char>(&fb),
std::istreambuf_iterator<char>());
}
精彩评论