Have a look here for how to write and read variable-length strings to and from streams.