Hi,
I'm trying to print to a file some data of objects and I'm trying to do this in pseudo xml format so my file would look like let's say:
<node>
data
</node>
I'm using write method:

fstream fout("my_file.txt");
fout.write("<name>", sizeof(7));
fout.write("\n", sizeof(2));
fout.write(this->name(), sizeof(this->name()).length());
fout.write("\n", sizeof(2));
fout.write("<name>", sizeof(8));

which I was convinced should produce output as I described above. Unfortunetly it is not the case and my output look like this:

"<na
Odin
name

I personally feel that it has to do with '<' character but I don't know where to hit and also another problem with this task is that when I set the opening mode to binary nothing is written to this file.
Thank you for any help.

It's gonna work, once you get rid of those "sizeof"'s, which actually always return the size of integer. The right invocation might look like:
<code>
fout.write("<name>", 7);
</code>

Syntax: write(char_array,no_of_bytes_to_be_written);

char ar[]="Hello";
  fout.write(ar,1); // It will write  H
  fout.write(ar,2); // it will write  He
  fout.write(ar,3); // It will write  Hel
  fout.write(ar,strlen(ar));
  ....

sizeof(2) or sizeof(7) will return number of bytes used to hold integer value - 4 bytes.
PS: avoid the use of sizeof() operator.

Guys, thank you very much. Most appreciated. Great crew.

Hi, it's me again,
Another two problems which I'm having with this example is that when in ofstream constructor I specify mode as binary:
ofstream fout("my_file.txt", ios_base::binary);
nothing is written to a file (at least I can't see there anything)
and another problem which I cannot cross is that I cannot write integers to a file only strings. What I'm doing is:
int a = 1;
fout.write(reinterpret_cast<char*>(&a), sizeof(int));
after this nothing is written in the file;
Hope someone will help me with this kerfuffle.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.