[LC++]geting a "char *" (not const) from a string.data()

Chris Vine chris at cvine.freeserve.co.uk
Sat Jul 28 11:07:08 UTC 2001


On Thursday 26 July 2001 19:31, Jan Pfeifer wrote:
> hi :)
>
> i need to read a whole file to a string and return it, but i can't imagine
> how to do this without having to read the whole file to a char* buffer
> first and assigning (copying) to a string later. Is there another way
> around ?
>
> the code (without error checking):
>
> string file_read( string filename )
> {
>   unsigned filesize = file_size( filename ); // suppose file_size() defined
>   char *buf = new char[ filesize ];
>   int fd = open( filename, O_RDONLY );
>   read( fd, buf, filesize );
>   string ret( buf, filesize );
>   delete[] buf;
>   return ret;
> }
>
> is there a way round without having to allocate and copy buf ?

I am not sure what you are trying to do or why you are trying to do it, but 
with vector<char> you can take the address of the first character and 
directly address the contents of the allocated memory (previously allocated 
with vector<char>::resize()).  It is not a requirement of the C++ standard 
that all memory in a vector is contiguous, but that was intended, I think all 
implementations do it, and the matter will be made explicit in a forthcoming 
correction to the standard.

Thus with a vector<char> you could do --

  std::vector<char> vec;
  vec.resize(filesize);
  read(fd, &vec[0], filesize);

I don't think the same contiguity guarantees are made about std::strings, but 
probably the same applies but with less portability.  You can put binary data 
in a std::string ('\0' is not a terminating character), but nonetheless if 
you have binary data why are you putting it in a string?

Chris.



More information about the tuxCPProgramming mailing list