In the program below I'm a little confused with these two lines -> fbin.seekp(n * recsize);
& fbin.write(reinterpret_cast<char*>(&age), sizeof(int));
In the first one, why would we start writing to the file at position n * recsize instead of position 0? I would think that we would start writing at 0 and the jump to n * recsize for writing to the next block each time a write is made. And on the second line I'm confused about most of it. I've done simple type casting but what the heck is this? What is reinterpret_cast? Is it function, it doesn't have the syntax of one or is it just a built in keyword? Why are we casting as a char pointer or are we casting as a char pointer and what's the (&age)
all about? Thanks.
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int get_int(int default_value);
char name[20];
int main()
{
char filename[81];
int n;
int age;
int recsize = sizeof(name) + sizeof(int);
cout << "Enter file name: ";
cin.getline(filename, 80);
// open file for binary read and write
fstream fbin(filename, ios::binary | ios::in | ios::out);
if(!fbin)
{
cout << "Could not open file " << filename;
return -1;
}
//Get record number to write to
cout << "Enter file record number: ";
n = get_int(0);
// get data from end user
cout << "Enter name: ";
cin.getline(name, 19);
cout << "Enter age: ";
age = get_int(0);
// write data to the file
fbin.seekp(n * recsize);
fbin.write(name, 20);
fbin.write(reinterpret_cast<char*>(&age), sizeof(int));
return 0;
}
// get integer function
// get an int value from keyboard; return default value
// if user enters 0-length string
//
int get_int(int default_value)
{
char s[81];
cin.getline(s, 80);
if(strlen(s) == 0)
return default_value;
return atoi(s);
}