This example writes binary data to a file. It prompts for a record #, name, age. Everything works except I'm getting garbage for the age.
Here's the code:
Code:
#include <iostream>
#include <fstream>
using namespace std;
int get_int(int default_value) ;
int main() {
char filename[MAX_PATH + 1] ;
int n = 0;
char name[20] ;
int age = 0;
int recsize = sizeof(name) + sizeof(int);
cout << " Enter filename: ";
cin.getline(filename, MAX_PATH) ;
// Open file for binary write.
fstream fbin(filename, ios::binary | ios::out);
if (!fbin) {
cout << "Could not open " << filename << endl ;
system(" PAUSE" ) ;
return - 1;
}
// Get record number to wri te to.
cout << "Enter file record number: ";
n = get_int(0) ;
// Get data from end user.
cout << "Enter name: " ;
cin.getline(name, sizeof(name) - 1) ;
cout << "Enter age: " ;
age = get_int(0) ;
// Write data to the file.
fbin.seekp(n * recsize) ;
fbin.write(name, si zeof(name) - 1) ;
fbin.write((char*)(&age) ,sizeof(int)) ;
fbin.close() ;
system("PAUSE" ) ;
return 0;
}
#define COL_WIDTH 80 // 80 is typical column width
// Get integer function
// Get an integer from keyboard; return default
// value if user enters 0-l ength string.
//
int get_int(int default_value) {
char s[COL_WIDTH+1] ;
cin.getline(s, COL_WIDTH) ;
if (strlen(s) == 0)
return default_value;
return atoi (s) ;
}
I thought the problem might be with this line(10):
int recsize = sizeof(name) + sizeof(int);
where sizeof(int) should be sizeof(age)
and this line of code as well:
fbin.write((char*)(&age) ,sizeof(int)) ;
where sizeof(int) should be sizeof(age)
I made the changes and tried it and the same garbabe for the age output.
Any ideas why this isn't working?