   C++ File contents to string
  Hi,I need to put the entire contents of a file to a string through a function. So far I haven't been able to return anything from the function. If this had been PHP I would have been done already.I was hoping if someone has any good ideas of how to do this the easiest way?The function should do this:1. Open the file requested2. Read the entire contents to a string(3. Do whatever with the string (remove stuff, split it up etc.))4. Return the (original) string for use with the rest of the code.I am using Microsoft Visual Studio 2005.Also any time I use "string" when defining a function (as a variable), it won't compile. It's quite annoying that you can't pass a string to a function.Please help!   
Quote:Also any time I use "string" when defining a function (as a variable), it won't compile. It's quite annoying that you can't pass a string to a function.In C++, strings are not a built-in type, but a standard library component. You must #include <string> and refer to the type as std::string.// Headers used by read_from_stream#include <string> // For std::string#include <deque>  // For std::deque#include <istream>// For std::istream#include <iterator>    // For std::istreambuf_iterator// Headers also used by main.#include <fstream>// For std::ifstreamvoid read_from_stream(std::istream& is, std::string& str){   std::istreambuf_iterator<char> begin(is); // The beginning of the stream   std::istreambuf_iterator<char> end;  // The end of the stream std::deque<char> buf(begin, end);    // Load the data into a buffer.   str.assign(buf.begin(), buf.end());  // Copy the buffer into the string.}int main(){   std::ifstream my_file("helloworld.txt");   std::string my_file_contents;   read_from_stream(my_file, my_file_contents);}There are a few optimizations there:* using an istreambuf iterator to directly grab the raw data.* loading into a deque then assigning to the string to minimize reallocations. If that uses too much memory for your tastes, directly do str.assign(begin, end);* using a reference parameter to avoid copying the string.   ;  If you are willing to use ManagedC++, its brutally easy.int main(array<System::String ^> ^args){System::String ^filename = gcnew System::String("StringReader.cpp");System::IO::StreamReader ^ sr = gcnew System::IO::StreamReader(filename);System::Collections::ArrayList lines = gcnew System::Collections::ArrayList();while((sr->EndOfStream) == false)lines.Add(sr->ReadLine());sr->Close();delete sr;for(int i = 0; i < lines.Count; i++)System::Console::WriteLine(lines);}Granted, once you start mixing managed and unmanaged code, you can kiss porting to another platform (aka, linux) goodbye.   