C++ read File Reads file contents into the method in the string string

  • 2020-06-07 04:58:04
  • OfStack

As shown below:


#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
 
#include <stdlib.h>
using namespace std;
 
 
// Read in from file to string In the 
string readFileIntoString(char * filename)
{
ifstream ifile(filename);
// Read the file into ostringstream object buf In the 
ostringstream buf;
char ch;
while(buf&&ifile.get(ch))
buf.put(ch);
// Returns an object with a stream buf Associated string 
return buf.str();
}
 
int main()
{
// The file name 
char * fn="a.txt";
string str;
str=readFileIntoString(fn);
cout<<str<<endl;
system("pause");
 
}

Related articles: