zwol: ((mad) science)
[personal profile] zwol

Is there any portable way to read [as in the system call] from a file directly into a C++ standard string? One would like to do something like

  str.reserve(filesize);
  got = ::read(fd, str.data(), str.capacity());
  str.enlarge_to_cover(got);

(error handling and loop until EOF omitted for clarity) but I can't actually find a method that does enlarge_to_cover(). Also, data() returns a read-only pointer.

... why am I still awake?

Date: 2008-02-29 02:42 pm (UTC)
From: [identity profile] queenpam.livejournal.com
I hope your computer is still on eastern time....

Date: 2008-02-29 05:26 pm (UTC)
From: [identity profile] zwol.livejournal.com
Yes, yes it was. Heh.

Date: 2008-02-29 06:11 pm (UTC)
From: [identity profile] echristo.livejournal.com
stat(fileName->c_str(), &statInfo);
FD = ::open (fileName->c_str(), O_RDONLY);
size = statInfo.st_size;
file = (char *)malloc (size);
int bytes_read = ::read (FD, file, size);

would save the problem of having to redo the size. Replace malloc
with str.reserve...

should work i think.

Date: 2008-02-29 06:39 pm (UTC)
From: [identity profile] zwol.livejournal.com
... that part's not the problem. The problem is there doesn't seem to be any way to tell a C++ string "okay, there is now meaningful data in your buffer." reserve() reserves space but doesn't include it in size(); there is a method whose name I forget that increases size() -- but zeroes the space, overwriting anything I might have put in there with read().

Plus, data() and c_str() are read-only. Gah.

(I suppose I could use the method whose name I forget and then overwrite with read() but that's not going to be any faster than using a scratch char[] and copying.)

Date: 2008-02-29 06:53 pm (UTC)
From: [identity profile] echristo.livejournal.com
oh, right. um... can't recall either.

Bah.

Date: 2008-03-05 08:01 pm (UTC)
brooksmoses: (Default)
From: [personal profile] brooksmoses
Oddly enough, while istreams provide a getline() method for strings, they don't seem to provide a read() one.

April 2017

S M T W T F S
      1
2345678
9101112131415
16171819 202122
23242526272829
30      

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 10th, 2026 10:51 pm
Powered by Dreamwidth Studios