user466534
user466534

Reputation:

question about string to file

here is code

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
  ofstream out("test", ios::out | ios::binary);

  if(!out) {
    cout << "Cannot open output file.\n";
    return 1;
  }

  double num = 100.45;
  char str[] = "www.java2s.com";

  out.write((char *) &num, sizeof(double));
  out.write(str, strlen(str));

  out.close();

  return 0;
}

i dont understand only this

out.write((char *) &num, sizeof(double));

why we need (char *)&num?or sizeof(double)?

Upvotes: 0

Views: 108

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490138

You need them because you're accessing the component bytes that make up the double. write expects to receive a char *, so you cast the address to char *. Since it doesn't know the type of object being written (with the right cast, write will accept a pointer to almost anything), so you need to tell it how many bytes make up the object to be written.

Upvotes: 1

James Curran
James Curran

Reputation: 103505

write takes two parameters, a char* and a length.

&num is actually a double*. It's the value we want, but it's the wrong type, and the compiler would complain. The (char*) tells the compiler to treat this as a char*. Basically, it says to the compiler "Shutup. I know what I'm doing".

sizeof(double) is the size of the double in characters. (Usually, this is 8).

Together, they say to write the 8 bytes starting at the address given by &num. (or in other words, write out the bytes that make up num)

Upvotes: 3

Related Questions