casting and reading from binary files

Hi guys,

I have a function that writes data to a file,that data is two strings and an int, I do this in binary mode.

I give a snippet below of what I am confused by, so obviously int age is an integer and is 4 bytes in size on most machines, but in the read function I am casting the int to a char*

so my question is how is this done and why is this done?

I thought by casting the age variable to a char* it would now be a char* but that doesn't seem to be the case, it seems to still be an integer even after this cast - in.read((char*)&age,sizeof(int));

I thought that in the arguments I casted age to a char pointer so shouldn't it be a char pointer from now on???( it doesn't seem to be) I thought I would need to re cast it to a int in order to use it?

thanks



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    int nameSize = 0;
    int numberSize = 0;
    int age = 0;


    while(in.tellg() < fileSize){

        in.read((char*)&nameSize,sizeof(int));
        char* nameC = new char[nameSize];
        in.read(nameC,nameSize);

        in.read((char*)&age,sizeof(int));
        cout << "age" << age << endl;

Last edited on
You aren't casting an int to a char*. You are casting an int* to a char*. A char* is basically a byte pointer, which is needed by the read/write routines since they read/write a given number of bytes.
sorry I should have said int*

but am I truly casting it? and how come I can use the age variable as if no cast was ever done?( after the read function)

Casting doesn't permanently change the variable. It's just to temporarily see the value (or address) in a different form.

The important difference between int* and char* is how they respond to pointer arithmetic. int* pointers increase by 4 bytes for every 1 added (assuming 32-bit ints). char* pointers increase by 1 when 1 is added.

Since the low-level read/write routines work on raw memory (and know nothing of ints, doubles, arrays, etc.) they need to be passed a char* and told exactly how many bytes to process.
oh ok, so (char*)&age doesn't permanently change the type of the variable
keeping the casted stuff around makes it simpler to read and handle. You don't have to do that, but its nice in larger problems to keep track of it all (using better names than I did here). And in a class that you serialize having the private member pointers keeps it organized etc. It saves having so much casting that its hard to follow, is the point.

int x;
const char* cp = (char*)&x; //do this once and get it out of the way.

file.read(cp, sizeof(int)); //many of these, no need to cast...
cout << x; //its what you read.

though its a lot better if you can read C structs that have all the file variables, just read all of them in a single go. That makes the whole binary file thing much more slick than the one-at-a-time approach. Youll see that soon.
Last edited on
Topic archived. No new replies allowed.