zwol ([info]zwol) wrote,
@ 2008-02-29 03:19:00
Previous Entry  Add to memories!  Tell a Friend!  Next Entry
irritating corner-case c++ question

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?



(Post a new comment)


[info]queenpam
2008-02-29 02:42 pm UTC (link)
I hope your computer is still on eastern time....

(Reply to this)(Thread)


[info]zwol
2008-02-29 05:26 pm UTC (link)
Yes, yes it was. Heh.

(Reply to this)(Parent)


[info]echristo
2008-02-29 06:11 pm UTC (link)
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.

(Reply to this)(Thread)


[info]zwol
2008-02-29 06:39 pm UTC (link)
... 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.)

(Reply to this)(Parent)(Thread)


[info]echristo
2008-02-29 06:53 pm UTC (link)
oh, right. um... can't recall either.

Bah.

(Reply to this)(Parent)


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

(Reply to this)


Create an Account
Forgot your login?
Login w/ OpenID
English • Español • Deutsch • Русский…