954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with writing to a file

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:

data

I'm using write method:
[code = C++]
fstream fout("my_file.txt");
fout.write("", sizeof(7));
fout.write("\n", sizeof(2));
fout.write(this->name(), sizeof(this->name()).length());
fout.write("\n", sizeof(2));
fout.write("", sizeof(8));
[/code]
which I was convinced should produce output as I described above. Unfortunetly it is not the case and my output look like this:

"

atch
Junior Poster in Training
58 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

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:

fout.write("", 7);

zautner
Newbie Poster
7 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

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.

__avd
Posting Genius (adatapost)
Moderator
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

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

atch
Junior Poster in Training
58 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

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(&a), sizeof(int));
after this nothing is written in the file;
Hope someone will help me with this kerfuffle.

atch
Junior Poster in Training
58 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You