> 2. This will not fail because there is a statement len++ for the '\0';
Except by doing so, you step off the end of the memory you allocated, write a \0 into someone else's memory, then get abnormal program termination.
You need to allocate len+1 slots if you want to read len items, then append a \0.
What do you mean that I am writing outside my memory. I can't see it in the code. After len++ I allocate memory: len-1 for all tokens and the last one for '\0'. I don't see that I am writing '\0' in someone's else's memory.
Originally Posted by Salem
And why is the program writing binary data, I have never declared ios_base::bin
read() and write() are for dealing in binary data, or bulk characters. But since you're casting, you don't have characters ready in the proper form, so it must be binary data.
> What do you mean that I am writing outside my memory.
You might seem to get lucky on a few attempts, but sooner or later, this kind of code will cause a crash.
int len = 10;
char *array = new char[len];
read( array, len ); // reads len chars, the array is full, no room for a \0
array[len] = '\0'; // oops, you lose, but maybe not immediately...
And how must I fix it, or is there a easier way to write and read wstrings and strings to a file?
Must I use operator<< and operator>>?
Well if you allocated len+1, then read len, that might be a start.
I already told you a solution, and so did CornedBee:
Originally Posted by Wicket
And operators << and >> are strictly for text and not for binary.
Originally Posted by CornedBee
But also try to fix the len problem as Salem mentions.
At last, it is working.
Thanks everyone, not only for the functions to get working but also to understand some more things.