sap
sap

Reputation: 73

read() function in c++ similar to c read()

Is there any method equivalent to c read() in c++? To illustrate my question, in C, if I have:

struct A{  
  char data[4];  
  int num;  
};

...and if I use:

A* a = malloc (sizeof(struct A));  
read (fd, a, sizeof(struct A));

I can directly populate my struct. Is there a way in c++ to achieve this without using c read() method? Methods in std::istream need char* as an argument, is there any method which takes void* as an argument?

Upvotes: 0

Views: 23586

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490338

The closest equivalent is almost certainly to use istream::read:

struct A {
  char data[4];
  int num;
};

A a;

std::ifstream in("somefile", std::ios::binary);

in.read((char *)&a, sizeof(a));

Note that this is equivalent to read in a number of ways you'd probably prefer it wasn't--for example, it'll probably break if you upgrade your compiler, and might break just from breathing a little wrong.

If you insist on doing it anyway, you probably at least want to hide the ugliness a little:

struct A { 
   char data[4];
   int num;

   friend std::istream &operator>>(std::istream &is, A &a) { 
       return is.read((char *)a, sizeof(a));
   }
};

Then other code will read an instance from a file with a normal insertion operator:

std::ofstream in("whatever", std::ios::binary);

A a;

in >> a;

This way, when you come to your senses and serialize your object a little more sanely, you'll only need to modify operator>>, and the rest of the code will remain unchanged.

friend std::istream &operator>>(std::istream &is, A &a) { 
// At least deals with some of the padding problems, but not endianess, etc.
    os.read(&a.data, sizeof(a.data));
    return os.read((char *)&a.num, sizeof(a.num));
}

Then the rest of the code that uses this doesn't need to change:

A a;
in >> a;  // remains valid

Upvotes: 1

Related Questions