Forum Navigation
Writing a string to a file and reading it back
Posted: 10/11/08 00:19:01Maybe something's wrong with me, but I'm consistently having an inordinate amount of trouble with simple file I/O tasks in Tango. This time, I simply want to write a string (of dynamic length) to a file and read it back in again.
Writing is simple enough:
auto stream = new DataOutput(new FileOutput(fname)); stream.put(mystring);An inspection of the created binary output shows an integer indicating the length of the string followed by the string bytes themselves; as expected.
Now, when I try to read the string back again, I get into trouble:
auto stream = new DataInput(new FileInput(fname)); char[] mystring; stream.get(mystring);This doesn't work because get() expects the array it is passed already to be allocated to a sufficient size. Clearly, I can't do this because I don't know before the call to get() how long the string will be!
I can think of some kludgy workarounds, but is there a clean and simple standard way to do this? Especially taking into account that I want to interleave this call with calls to other DataStream? methods like getInt etc? Maybe a templated method DataInput?.getArray(T)() which would return a newly allocated array of the given type would be helpful?