Topic: Using streams to read a file into a string


Author: lars@NOSPAM.netch.se (Lars Olofsson)
Date: 1998/02/03
Raw View
Hi!

I am looking for the best way to read a binary file from disk into a
basic_string<char> using streams.

[ mod note: I'm approving this article because it concerns new
  C++ features. Let's keep all discussion in terms of the standard
  C++ string and stream classes.  -sdc ]

One way is to use a temporary buffer. The code could look something
like this....

------------------------------------------------------------------------------

ifstream myFile("filename",  ios::binary);

myFile.seekg(0, ios::end);
long fileSize = myFile.tellg();
myFile.seekg(0, ios::beg);

char* buffer =  (char*) malloc(fileSize);  // Or maybe fileSize+1,
anyway -  not important.

myFile.read(buffer,  fileSize);
string myString(buffer);

-------------------------------------------------------------------------------

What I would LIKE to do is to be able to read the whole file into a
string without knowing anything about the size of the file, or having
to worry about allocating memory for any buffers.

Any ideas? Tips?

Thank you.

/Lars Olofsson
Software Developer.
Netch Techology, Lund, Sweden.




[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]