-
help with fileio
this is my code,,,,,,
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int pos=50;
int posy;
ofstream out;
out.open ("fileio6.txt");
out.write ( "hello",pos);
pos=out.tellp();
cout<< pos;
}
now it seems to do the job i want but when i check th text file this is what i get on the top line, i was ecpecting the hello but i don't know hy the rest is there.
hello fileio5.txt x@ X ÿÿÿÿ
if you could tell me why i would appreciate it llllloooooooootts :)
-
Because "hello" is only 5 chars, but you write out 50 ?
-
write() doesn't pay attention to what you are trying to write out, it just does it for you (since it is meant for binary output). So it doesn't know that you want it to stop when the terminating null character and the end of the character array is reached, it just thinks that it is supposed to write out 50 characters starting at the first character of the literal "hello". Everything after the first 6 is junk stuck in memory. (Notice that the literal "fileio6.txt" is also in memory around the same place as "hello".)
Assuming you don't want binary, use operator<< to write out your string. If you do want binary, then only write out the number of characters you want to write out.