I am working through the book C++ Without Fear and just got to the part where binary files are introduced. I created a program using binary files, but it can never successfully open the file. I tried some code straight from the CD that comes with the book and that had the same problem.
This is the line of code used to open the file:
Code:
fstream fileout(filename, ios::binary | ios::in | ios::out);
Any idea what is going on?
The only thing I can think of is that the file needs to already exist, but that is not true of text files, so I doubt that is the problem. If it is the problem, how would I create a binary file?
Thanks!
Below is my code, which is very similar to the code in the book.
Code:
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int get_int(int def);
main(){
int recsize, recnum;
char model[20], make[20], year[5];
int miles;
char filename[81];
recsize = sizeof(model) + sizeof(make) + sizeof(year) + sizeof(int);
cout << "Enter filename and press ENTER: ";
cin.getline(filename, 80);
fstream fileout(filename, ios::binary | ios::in | ios::out);
if(! fileout){
cout << "Error opening file.";
getchar();
return -1;
}
while(true){
cout << "Enter record to write to: ";
recnum = get_int(0);
fileout.seekp(recnum * recsize);
fileout.write(model, 20);
fileout.write(make, 20);
fileout.write(year, 5);
fileout.write(reinterpret_cast<char*>(&miles), sizeof(int));
}
fileout.close();
getchar();
return 0;
}
int get_int(int def){
char inpt_str[81];
int inpt;
cin.getline(inpt_str, 80);
if(strlen(inpt_str) == 0){
inpt = def;
}else{
inpt = atoi(inpt_str);
}
return inpt;
}