[LC++]geting a "char *" (not const) from a string.data()
Jan Pfeifer
janpf at yahoo-inc.com
Mon Jul 30 21:39:06 UTC 2001
actually i have a parsing function that receives a string (text). So i
want to read a whole text file into a string and pass it to the function.
But i wanted to do this without having to read the file into a char
buffer, and then copy to the string. I was wondering if there were, as you
said a way to do a "string::resize" and get a pointer to this data, so
that i could read the file directly there.
any idea ?
thanks for the answer,
jan
On Fri, 27 Jul 2001 22:32:07 +0100
Chris Vine <chris at cvine.freeserve.co.uk> wrote:
> 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.
> _______________________________________________
> This is the Linux C++ Programming List
> : http://lists.linux.org.au/listinfo/tuxcpprogramming List
>
>
More information about the tuxCPProgramming
mailing list