Link to Chapter 9 : File Handling - Database
Header file: #include<fstream>
Declaration: ifstream fin("data.txt"); //Input
ofstream fout("data.txt"); //Ouput
Read in: fin>>id>>price; //Read in one line
while(fin>>id>>price){ } //Read in entire file
Writing to file: fout<<id<<" "<<price<<endl;
Close file: fin.close();
fout.close();
Sample load and storefunctions (reading your data file into an array:
//Student Example for load
void load(){
n=0;
z=0;
ifstream studentFile("students.txt", ios::in);
ifstream courseFile("courses.txt", ios::in);
while(studentFile>>e[n].fname>>e[n].lname>>e[n].major>>e[n].gpa){
n++;}//WHILE
while(courseFile>>c[z].CRN>>c[z].title>>c[z].department>>c[z].room){
z++;}//WHILE
}//LOAD
//Employee Example for load
void load(){
ifstream fin("employee.txt",ios::in);
while(fin>>e[n].fname>>e[n].lname>>e[n].hourlyrate>>e[n].hoursworked){
e[n].netpay=e[n].hourlyrate*e[n].hoursworked;
n++;}//WHILE
}//LOAD
//Employee example for store
void store(){
ofstream fout("employee.txt",ios::out);
for(int i=0; i<n; i++){
if(e[i].fname!=" ")
fout<<e[i].fname<<" "<<e[i].lname<<"
"<<e[i].hourlyrate<<" "<<e[i .hoursworked<<endl;
}//FOR
}//STORE
//Student example for store
void store(){
ofstream studentFile("students.txt",ios::out);
for(int i=0; i<n; i++){
if(e[i].fname!=" ")
studentFile<<e[i].fname<<" "<<e[i].lname<<" "<<e[i].major<<" "<<e[i].gpa<<endl;
}//FOR
ofstream courseFile("courses.txt", ios::out);
for(int j=0; j<z; j++){
if(c[j].CRN!=" ")
courseFile<< c[j].CRN << " "<<c[j].title << " "<<c[j].department << " "<<c[j].room<<endl;
}//FOR
}//STORE