help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: <g++ 3.4.4> Problem with reading file into string


From: Ulrich Eckhardt
Subject: Re: <g++ 3.4.4> Problem with reading file into string
Date: Thu, 11 Aug 2005 15:53:02 +0200
User-agent: KNode/0.8.2

alexvn@users.sourceforge.net wrote:
> Here are two functions that read text and binary file into string.

Alex, apart from being really horrible C++[1], do these functions do
anything different except that they operate on different streams for
input? I just scanned them visually and could not find any other
differences...

Also, the code seems pretty convoluted, if anything there explicitly
matters, you completely fail to point out that difference.

Uli

[1]: I'm not sure if/where it matters, here's how it could have been
written differently:

> string txt_file_to_string ()

If the two functions are the same, you could as well have passed the stream
as reference:
  string to_string( std::ifstream& in)
or alternatively passing along the expected size.

> ostringstream oss;

Starting with this, there is an operator>> overload that takes a
streambuffer on the right hand side, so copying the file into that buffe
would be a mere
  in >> oss.rdbuf();

> vector<char> v (infile_txt_filesize);
>   fs_infile_txt.read(&v[0], infile_txt_filesize);

Could init the vector with the content of the file instead:
  vector<char> v( (istream_iterator<char>(in)), istream_iterator());

> ostream_iterator<char> out(oss);
>   copy (&v[0], &v[v.size()], out);

You're thinking too complicated:
  copy( v.begin(), v.end(), ostream_iterator<char>(oss));

>   return oss.str();

How about 
  return std::string( (istream_iterator<char>(in)), istream_iterator());
here? Alternatively, something like this:
  std::string res(infile_filesize);
  std::copy( istream_iterator<char>(in), istream_iterator(), str.begin());


-- 
http://gcc.gnu.org/faq.html
http://parashift.com/c++-faq-lite/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]