this is the input I made the following code for my cs project but i am facing some logical errors which i am unable to fix i tried a lot but still i am unable to fix it so please help me,,
as you can see in the picture above i entered male in sex but it is writing only ale in the file and there is a problem with the output
This is software which i made as a project for my practical exam it was working fine until my friend did some modifications to it whenever i am entering any record(using file) it is working fine(at least it seems to be) but when i am displaying the record some of the characters are missing i don't know why so please help me to fix it....*
thank you
#include<fstream.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
class patient
{
public:
int year,date,month;
int bno;
char na[20],street[20],city[20],sex[8];
patient()
{
bno=0;
year=0;
date=0;
month=0;
strcpy(na,NULL);
strcpy(city,NULL);
strcpy(street,NULL);
strcpy(sex,NULL);
}
void enterdata()
{
cout<<"\nENTER THE NAME OF THE PATIENT \t\t-----\t\t";gets(na);
cout<<"\nENTER GENDER\t\t\t\t-----\t\t";gets(sex);
cout<<"\nASSIGN A UNIQUE BED NO. \t\t-----\t\t"; cin>>bno;
cout<<"\nDATE OF BIRTH\nDATE \t\t\t\t\t-----\t\t";cin>>date;
cout<<"\nMONTH \t\t\t\t\t-----\t\t";cin>>month;
cout<<"\nYEAR \t\t\t\t\t-----\t\t";cin>>year;
cout<<"\nENTER STREET \t\t\t\t-----\t\t";gets(street);
cout<<"\nENTER CITY \t\t\t\t-----\t\t";gets(city);
}
void showdata()
{
clrscr();
cout<<" \t\t\tINFORMATION OF THE PATIENT\n";
for(int vg=0;vg<78;vg++)
cout<<"-";
cout<<"\n";
for(vg=0;vg<78;vg++)
cout<<"-";
cout<<"\n\n\t\t\tBED NO \t\t:-\t"<<bno;
cout<<"\n\n\t\t\tNAME \t\t:-\t"<<na;
cout<<"\n\n\t\t\tGENDER \t\t:-\t"<<sex;
cout<<"\n\n\t\t\tCITY \t\t:-\t"<<city;
cout<<"\n\n\t\t\tSTREET \t\t:-\t"<<street;
}
~patient()
{
bno=0;
year=0;
date=0;
month=0;
strcpy(na,NULL);
strcpy(city,NULL);
strcpy(street,NULL);
strcpy(sex,NULL);
}};
void main()
{
patient p,p1;
char ch,cna[20];
xy:
do
{
ifstream ifile;
ifile.open("file1.dat",ios::in);
ofstream ofile;
ofile.open("file1.dat",ios::app|ios::binary);
ofstream temp;
temp.open("temp1.dat",ios::app|ios::binary);
clrscr();
cout<<"\n\t\t\t***HOSPITAL MANAGEMENT SOFTWARE***"<<"\n";
cout<<"\n\t\t\t **Hospital Management Tasks**"<<"\n\n";
for(int st=0;st<80;st++)
cout<<"-";
for(st=0;st<80;st++)
cout<<"|";
for(st=0;st<80;st++)
cout<<"-";
cout<<"\n\n";
cout<<"\t\t\tPlease select a task to do...."<<"\n\n";
cout<<"\t\t\t1. Enter a new patient information ."<<"\n\n";
cout<<"\t\t\t2. View detail of existing patient ."<<"\n\n";
cout<<"\t\t\t3. Emergency"<<"\n\n";
cout<<"\t\t\t4. Discharge patient"<<"\n\n";
cout<<"\t\t\t5. Exit from the program ."<<"\n\n";
cout<<"\t\t\t6.ADMIN MODE"<<"\n\n";
cout<<"\t\t\tEnter your task serial :"<<"\n\n\t\t\t";
ch=getche();
switch(ch)
{
case '1': clrscr();
p.enterdata();
ofile.write((char*)&p,sizeof(p));
getch();
break;
case '2':
clrscr();
int k=0,cbno=0;
if(!ifile)
{
cout<<"\n unable to open file\n";
getch();
}
else
{
cout<<"\n ENTER THE NAME OF PATIENT\t\t\t-----\t\t";gets(cna);
cout<<"\n ENTER BED NUMBER\t\t\t\t-----\t\t";cin>>cbno;
ifile.clear();
ifile.seekg(0,ios::beg);
while(!ifile.eof())
{
ifile.read((char*)&p1,sizeof(p1));
if(cbno==p1.bno)
{
if(strcmpi(cna,p1.na)==0)
{
p1.showdata();
getch();
k=1;
break;
}
}
}
if(k!=1)
cout<<"\n NO SUCH RECORD PRESENT\n";
getch();
}
ifile.close();
break;
case '3':
clrscr();
temp.clear();
temp.seekp(0,ios::beg);
ifile.clear();
ifile.seekg(0,ios::beg);
p1.enterdata();
temp.write((char*)&p1,sizeof(p1));
while(!ifile.eof())
{
ifile.read((char*)&p,sizeof(p));
cout<<"\ndone writing\n";
cout<<"\n done";getch();
temp.write((char*)&p,sizeof(p));
}
ifile.close();
temp.close();
remove("file1.dat");
rename("temp1.dat","file1.dat");
break;
case '4' :
char ch;int pos=-1;
clrscr();
cout<<"\t\t\tDISCHARGE PATIENT\n";
if(!ifile)
{ clrscr();
cout<<"\n\n\t\t\t!!!!FAILED TO OPEN FILE!!!! \n";
getch();
}
else
{
cout<<"\n ENTER THE NAME OF PATIENT\t\t\t-----\t\t";gets(cna);
cout<<"\n ENTER BED NUMBER\t\t\t\t-----\t\t";cin>>cbno;
ifile.clear();
ifile.seekg(0,ios::beg);
while(!ifile.eof())
{
ifile.read((char*)&p1,sizeof(p1));
if(cbno==p1.bno)
{
if(strcmpi(cna,p1.na)==0)
{ pos=ifile.tellg();
p1.showdata();
cout<<"\n \t\t ARE YOU SURE TO DISCHARGE THIS PATIENT(y/n)? \n \t\t";
ch=getche();
getch();k=1;
break;
} }
}
if(k!=1)
{ cout<<"\n NO SUCH RECORD PRESENT\n";
getch();
ifile.close();
goto xy;}
ifile.close();
if(ch=='y'||ch=='Y')
{
ifile.open("file1.dat");
while(!ifile.eof())
{
ifile.read((char*)&p1,sizeof(p1));
if(pos!=ifile.tellg())
temp.write((char*)&p1,sizeof(p1));
}
ifile.close();
temp.close();
remove("file1.dat");
rename("temp1.dat","file1.dat");
} }
break;
case '5':
break;
case '6':
char id[5];
clrscr();
cout<<"\n ENTER THE ADMIN ID\t\t---- ";
gets(id);
if(strcmp(id,"70176")==0)
{
cout<<"\n\n\n\t\t\t VERIFICATION SUCCESSFUL ";
getch();
if(!ifile)
{cout<<"unable to open file";
getch();}
else
{
ifile.clear();
ifile.seekg(0,ios::beg);
while(!ifile.eof())
{ ifile.read((char*)&p,sizeof(p));
p.showdata();
getch();
}
} ifile.close(); }else
{ cout<<"\n\n\t\t\t!!!!!! FAILED TO VERIFY!!!!!!\n"; getch();}
break;
default :
cout<<"\n ERROR \n";
cout<<"\a";
getch();
break;}}
while(ch!='5');
}
if the code is not clear here is the link to download it https://drive.google.com/file/d/1hTz3awCDaW-40ewEbpK1VHYa6k5SoD-d/view?usp=sharing
When i execute the program and select option number 2 it reads the data from the file successfully but when i select the option number 2 for the second time , third time and so on... nothing comes up and it returns back to the menu.
I have tried so many times, same error comes every time. PLEASE HELP. Thanks to all in advance. love all.
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <iomanip>
#include <iostream>
using namespace std;
//class for database functions
class group
{
private:
struct person {
char flag;
char empcode[5];
char name[10];
int age;
float sal;
}p;
public:
fstream file,t_file;
ifstream fin;
ofstream fout;
group();
void addrec();
void listrec();
void modirec();
void delrec();
void recovrec();
};
//main function
int main()
{
char choice;
group g;
do
{
system("cls");
cout<<"1.Add Records"<<endl;
cout<<"2.List Records"<<endl;
cout<<"3.Modify Records"<<endl;
cout<<"4.Delete A Record"<<endl;
cout<<"5.Recover Deleted Records"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Your choice ?: ";
cin>>choice;
system("cls");
switch(choice)
{
case '1':
g.addrec();
break;
case '2':
g.listrec();
break;
case '3':
g.modirec();
break;
case '4':
g.delrec();
break;
case '5':
g.recovrec();
break;
case '6':
exit(0);
}
} while(choice!=6);
return 0;
}
//default constructor
group::group()
{
file.open("EMP.DAT",ios::in|ios::out|ios::binary);
p.flag=' ';
if(!file)
cerr<<"Unable to open file";
}
//Add records at the end
void group::addrec()
{
char ch;
cout<<"Do You Want To Erase Previous Records ?: ";
cin>>ch;
if(ch=='y'||ch=='Y')
remove("EMP.DAT");
fout.open("EMP.DAT",ios::binary);
fout.seekp(0L,ios::end);
system("cls");
do
{
cout<<"Enter Emp_Code, Name, age, Salary"<<endl;
cin>>p.empcode>>p.name>>p.age>>p.sal;
fout.write((char*)&p,sizeof(p));
cout<<"Add another record ?: ";
cin>>ch;
} while(ch=='y'||ch=='Y');
fout.close();
}
//list all the records
void group::listrec()
{
int j=0;
//position get pointer at beginning
//fin.open("EMP.DAT",ios::binary);
file.seekg(0L,ios::beg);
while(file.read((char*)&p,sizeof(p)))
{
if(p.flag!='*')
{
cout<<"\nRecord N. "<<++j;
cout<<"\nEmp Code: "<<p.empcode;
cout<<"\nName: "<<p.name;
cout<<"\nAge: "<<p.age;
cout<<"\nSalary: "<<p.sal<<endl;
}
}
cin.ignore();
getchar();
}
//modifies a given record from file
void group::modirec()
{
char code[5];
int count=0;
long int pos;
cout<<"Enter Emp Code";
cin>>code;
file.open("EMP.DAT",ios::in|ios::out|ios::binary);
file.seekg(0,ios::beg);
//search an employee
while(file.read((char*)&p,sizeof(p)))
{
//if record is found
if(strcmp(p.empcode,code)==0&&p.flag==' ')
{
//recieve new data
cout<<"Enter new Data: "<<endl;
cout<<"Enter Emp_Code, Name, age, Salary"<<endl;
cin>>p.empcode>>p.name>>p.age>>p.sal;
//position put pointer to overwrite record
pos=count*sizeof(p);
file.seekp(pos,ios::beg);
file.write((char*)&p,sizeof(p));
file.close();
cout<<endl<<"Press Any Key...";
getchar();
return;
}
count++;
}
file.close();
cout<<endl<<"No Employee In File With Code: "<<code;
cout<<endl<<"Press Any Key...";
getchar();
}
//marks a record for deletion
void group::delrec()
{
char code[5];
long int pos;
int count =0;
cout<<"Enter Emp Code";
cin>>code;
file.open("EMP.DAT",ios::in|ios::out|ios::binary);
//position pointer at beginning
file.seekg(0L,ios::beg);
//search an employee
while(file.read((char*)&p,sizeof(p)))
{
//if record is found
if(strcmp(p.empcode,code)==0&&p.flag==' ')
{
p.flag='*';
//position put pointer
pos=count*sizeof(p);
file.seekp(pos,ios::beg);
file.write((char*)&p,sizeof(p));
file.close();
return ;
}
count++;
}
cout<<endl<<"No Employee In File With Code: "<<code;
file.close();
cout<<endl<<"Press Any Key...";
getchar();
}
//unmarkmarks a record
void group::recovrec()
{
char code[5];
long int pos;
int count =0;
cout<<"Enter Emp Code";
cin>>code;
file.open("EMP.DAT",ios::in|ios::out|ios::binary);
//position pointer at beginning
file.seekg(0L,ios::beg);
//search an employee
while(file.read((char*)&p,sizeof(p)))
{
//if record is found
if(strcmp(p.empcode,code)==0&&p.flag=='*')
{
p.flag=' ';
//position put pointer
pos=count*sizeof(p);
file.seekp(pos,ios::beg);
file.write((char*)&p,sizeof(p));
file.close();
return ;
}
count++;
}
file.close();
cout<<endl<<"No Employee In File With Code: "<<code;
cout<<endl<<"Press Any Key...";
getchar();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Q :Why is not this code working properly?
I have implemented file handling in C++ language.
I have created a complete file of the car. Through this code, we can store new data, delete old one, search a particular data about the car.The problem is that this code compiles successfully but during runtime, its execution stops and display an error message. I request kindly help me in removing runtime error from this code.
CODE:
#include<iostream>
#include<string.h>
#include<conio.h>
#include<fstream>
using namespace std;
struct car
{
char name[20];
int model;
string color;
int car_id;
string size;
float weight;
int price;
};
void getdata(car&); //function declaration
void showdata(car&); //function declaration
void searchdata(); //function declaration
void deleterecord(); //function declaration
void modify(); //function declaration
void readdata(); //function declaration
void writedata(); //function declaration
int main()
{
char ch;
cout<<"\nEnter w to write record ";
cout<<"\nEnter r to read record";
cout<<"\nEnter m to modify record";
cout<<"\nEnter s to search record";
cout<<"\nEnter d to delete record";
cout<<"\n\nEnter your choice :";
cin>>ch;
switch(ch)
{
case 'w':
{
writedata();
break;
}
case 'r':
{
readdata();
break;
}
case 's':
{
searchdata();
break;
}
case 'd':
{
deleterecord();
break;
}
case 'm':
{
modify();
break;
}
default:
{
cout<<"\nWrong choice";
}
}
return 0;
}
void getdata(car &ccc)
{
cout<<"Please enter name of car :";
cin>>ccc.name;
cout<<"Please enter model number of car:";
cin>>ccc.model;
cout<<"Enter color of car:";
cin>>ccc.color;
cout<<"Enter id number of car:";
cin>>ccc.car_id;
cout<<"Enter size of car :";
cin>>ccc.size;
cout<<"Enter weight of a car :";
cin>>ccc.weight;
cout<<"Enter price of a car :";
cin>>ccc.price;
}
void showdata(car &ccc)
{
cout<<"\nName of car is :";
puts(ccc.name);
cout<<"\nModel number of car is :"<<ccc.model;
cout<<"\nColor of car is :"<<ccc.color;
cout<<"\nID number of car is :"<<ccc.car_id;
cout<<"\nSize of car is :"<<ccc.size;
cout<<"\nWeight of car is :"<<ccc.weight;
cout<<"\nPrice of car is :"<<ccc.price;
}
void writedata()
{
ofstream file;
char ch='y';
car ccc;
file.open("carinformation.dat",ios::binary | ios::out | ios::app);
while(ch=='y'|| ch=='Y')
{
getdata(ccc);
file.write((char*)&ccc,sizeof(ccc));
cout<<"\nDo you want to countine?";
cin>>ch;
}
file.close();
}
void readdata()
{
int count=0;
ifstream file;
car ccc;
file.open("carinformation.dat",ios::binary | ios::in);
if(!file)
{
cout<<"File not found";
exit(0);
}
else
{
file.read((char*)&ccc,sizeof(ccc));
while(!file.eof())
{
showdata(ccc);
file.read((char*)&ccc,sizeof(ccc));
count++;
}
cout<<"Number of records are :"<<count;
}
file.close();
}
void searchdata()
{
car ccc;
ifstream file;
char n_c[20];
cout<<"Enter name of car :";
cin>>n_c;
file.open("carinformation.dat",ios::binary | ios::in);
if(!file)
{
cout<<"File nnot found";
exit(0);
}
else
{
file.read((char*)&ccc, sizeof(ccc));
while(!file.eof())
{
if(strcmp(n_c,ccc.name)==0)
{
showdata(ccc);
}
file.read((char*)&ccc, sizeof(ccc));
}
}
file.close();
}
void modify()
{
car ccc;
fstream file;
char n_c[20];
file.open("carinformation.dat",ios::binary | ios::in | ios::out);
cout<<"\nEnter name of car that should be searched:";
cin>>n_c;
if(!file)
{
cout<<"File not found";
exit(0);
}
else
{
file.read((char*)&ccc,sizeof(ccc));
while(!file.eof())
{
if(strcmp(n_c,ccc.name)==0)
{
file.seekg(0, ios::cur);
cout<<"Enter new record :\n";
getdata(ccc);
int i=file.tellg();
int j=sizeof(ccc);
int k=i-j;
file.seekp(k);
file.write((char*)&ccc, sizeof(ccc));
}
}
}
file.read((char*)&ccc, sizeof(ccc));
file.close();
}
void deleterecord()
{
int count=0;
car ccc;
int c_id;
cout<<"Please enter car id :";
cin>>c_id;
ifstream file;
file.open("carinformation.dat" ,ios::binary| ios::in);
ofstream file2;
file2.open("New carinformation.dat", ios::binary| ios::out);
while(file.read((char*)&ccc,sizeof(ccc)))
{
if(ccc.car_id!=c_id)
{
file2.write((char*)&ccc ,sizeof(ccc));
count++;
}
}
cout<<"Number of records are :"<<count;
file2.close();
count=0;
file2.open("New carinformation.dat", ios::binary| ios::in);
file.read((char*)&ccc,sizeof(ccc));
while(!file.eof())
{
count++;
showdata(ccc);
file.read((char*)&ccc,sizeof(ccc));
}
cout<<"Number of records are :"<<count;
file.close();
file2.close();
remove("carinfomation.dat");
rename("New carinformation.dat", "carinformation.dat");
file.open("carinformation.dat", ios::binary | ios::in);
file.read((char*)&ccc, sizeof(ccc));
while(!file.eof())
{
count++;
showdata(ccc);
file.read((char*)&ccc, sizeof(ccc));
}
cout<<"Number of records are :"<<count;
}
Class car has std::string fields which hold pointers to heap-allocated memory. So saving it to file by writing raw bytes file.write((char*)&ccc,sizeof(ccc)); is not going to work. And, what is more important, reading them later file.read((char*)&ccc, sizeof(ccc)); will fill string objects with invalid pointer values. You need to store fields one by one and read them one by one carefully validating input data.
There is a difference between "string" and "string.h". Delete two characters, ".h" and see if your code works.
<string.h> contains functions like strcpy, strlen for C style null-terminated strings.
<string> contains std::string, std::wstring plus other classes.
You need to initialize your struct, heres an example for your readdata(), look at the changes and figure out how to fix the rest of the program:
void readdata()
{
int count=0;
ifstream file;
car *ccc = new car();
file.open("carinformation.dat",ios::binary | ios::in);
if(!file)
{
cout<<"File not found";
exit(0);
}
else
{
file.read((char*)ccc,sizeof(*ccc));
while(!file.eof())
{
showdata(*ccc);
file.read((char*)ccc,sizeof(*ccc));
count++;
}
cout<<"Number of records are :"<<count;
}
file.close();
}
code
#include<iostream>
#include<fstream>
#include<conio.h>
#include<string>
using namespace std;
class student
{
int admno;
char name[20];
// char address[20];
//string name;
public:
void getdata()
{
cout<<"\n\nEnter The Name of The Student ";
//gets(name);
//cin.ignore();
cin>>name;
cout<<"\nEnter The admission no. ";
cin>>admno;
// getch();
}
void showdata()
{
cout<<"\nAdmission no. : "<<admno;
cout<<"\nStudent Name : "<<name<<endl;
//puts(name);
}
void display()
{
//student obj;
ifstream fp1;
fp1.open("student.dat",ios::binary);
while(fp1.read((char*)this,sizeof(*this)))
{
this->showdata();
fp1.read((char*)this,sizeof(*this));
}
fp1.close();
}
void add()
{
ofstream fp2;
fp2.open("student.dat",ios::binary|ios::app);
this->getdata();
fp2.write((char*)this,sizeof(*this));
fp2.close();
}
};
int main()
{
student obj;
//system("cls");
cout<<"\n1. Add new student";
cout<<"\n2. View all student";
cout<<"\n3. Search student";
cout<<"\n4. modify student";
cout<<"\n5. delete student";
cout<<"\n6. Exit";
cout<<"\n\nEnter your choice";
int ch;
cin>>ch;
switch(ch)
{
case 1:
obj.add();
break;
case 2:
obj.display();
//b.viewbook();
break;
default:
cout<<"Enter Valid choice";
}
return 0;
}
problem:
when I enter the data in file, the data is written to the file only in the alternate steps.
at the first run and enter the data it is OK and in second run to add the student, the data isnot written in the file and again in the next step it writes properly and it continues to give proper output in alternate addition.
You should put your switch inside a loop:
bool exitLoop = false;
while(!exitLoop) {
int ch;
cin>>ch;
switch(ch) {
case '1':
obj.add();
break;
case '2':
obj.display();
//b.viewbook();
break;
case '6':
exitLoop = true;
break;
default:
cout<<"Enter Valid choice";
}
}
Also note how to handle character inputs: 1 != '1'
This is the whole program. Right now,the delete function does not write to the temp file. I'll try to change str array to string and see if it helps.
The program is supposed to read write edit search and sort binary file with structures.
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include<string>
#include<limits>
#include<iomanip>
#include<stdio.h>
#include <errno.h>
using namespace std;
const int SIZE=40;
char typedef str[SIZE];
char fname[]="c:/solident.dat";
char tname[]="c:/temp.dat";
struct Rec{int id;str lname,fname;};
//prototypes
void menu(string&);
void engine(string&,Rec&,fstream&,fstream&,int,char[],char[]);
void openFile(char[]);
void addRec(Rec&,char[]);
void delAll(char[]);
void listAll(Rec&,fstream &,char[]);
void appRec(Rec&,fstream &,char[]);
void delRec(Rec&,fstream &, fstream &,char[],char []);
void srcRec(Rec&,fstream& ,char[]);
void modRec(Rec &J,fstream &outfile, char fname[]);
void sort();
int main(int argc, char *argv[])
{
string choice;
Rec Student;
fstream infile;
fstream outfile;
do
{
menu(choice);
engine(choice,Student,infile,outfile,SIZE,fname,tname);
} while(choice[0]!='0');
system("PAUSE");
return EXIT_SUCCESS;
}
//function menu
void menu(string &choice)
{
cout<<"\n\n\n\t\t========================";
cout<<"\n\n\t\tMENU \n";
cout<<"\n\t\t========================\n\n";
cout<<"\t\t[1] Open/check file\n";
cout<<"\t\t[2] Add records\n";
cout<<"\t\t[3] Append records\n";
cout<<"\t\t[4] Search for a record\n";
cout<<"\t\t[5] Delete a record\n";
cout<<"\t\t[6] Delete all records\n";
cout<<"\t\t[7] Modify a record\n";
cout<<"\t\t[8] List all records\n";
cout<<"\t\t[9] Sort all records\n";
cout<<"\t\t[0] Exit\n";
cout<<"\n\t\t========================= \n";
cout<<"\t\tYour choice :";
getline(cin,choice);
while (choice[0] !='1' && choice[0] !='2' &&choice[0] !='3' &&choice[0] !='4' &&choice[0] !='5' &&choice[0] !='6' &&choice[0] !='7' &&choice[0] !='8' &&choice[0] !='9' &&choice[0] !='0' )
{
cout<<"\n\t\t"<<choice<<" is invalid!";
cout<<"\n\t\tEnter correct choice: ";
getline(cin,choice);
}
cout<<"\n\t\t========================= \n\n";
}
//function
void engine(string &choice,Rec &J,fstream &infile,fstream &outfile,int SIZE,char fname[],char tname[])
{
switch (choice[0]){
case '1':
{
cout<<"Executing number "<<choice<<":"<<"Open/check file\n"<<endl;
openFile(fname);
break;
}
case '2':
{
cout<<"Executing number "<<choice<<":"<<"Add records\n"<<endl;
addRec(J,fname);
break;
}
case '3':
{
cout<<"Executing number "<<choice<<":"<<"Append records\n"<<endl;
appRec(J,outfile,fname);
break;
}
case '4':
{
cout<<"Executing number "<<choice<<":"<<"Search for a record\n"<<endl;
srcRec(J,infile,fname);
break;
}
case '5':
{
cout<<"Executing number "<<choice<<":"<<"Delete a record\n"<<endl;
delRec(J,infile, outfile,fname,tname);
break;
}
case '6':
{
cout<<"Executing number "<<choice<<":"<<"Delete all records\n"<<endl;
delAll(fname);
break;
}
case '7':
{
cout<<"Executing number "<<choice<<":"<<"Modify a record\n"<<endl;
modRec(J,outfile,fname);
break;
}
case '8':
{
cout<<"Executing number "<<choice<<":"<<"List all records\n"<<endl;
listAll(J,infile,fname);
break;
}
case '9':
{
cout<<"Executing number "<<choice<<":"<<"Sort all records\n"<<endl;
sort();
break;
}
default:exit(0);
}
}
//function
void openFile(char fname[])
{
cout<<"\nOpening file"<<fname<<"..."<<endl;
//confirm if file exists and opens
fstream infile;
fstream outfile;
infile.open(fname,ios::in|ios::binary);
if (infile.is_open())
{
cout<<"File "<<fname<<" exists, and was opened succesfully.";
}
infile.close();
//if fail ask to create
if (infile.fail())
{
cout<<"File does not exist. Create? [Y]/[N]";
char ch;
cin>>ch;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if yes then create file
if(ch=='y'|| ch=='Y')
outfile.open(fname,ios::out| ios::binary);
//if not created display error
if (outfile.fail())
{
cout<<"Error: File not created";
}
//else confirm creation of file
cout<<"File "<<fname<<" has been created.\n\n";
outfile.close();
}
}
//function
void addRec(Rec&J,char fname[])
{
fstream outfile;
outfile.open(fname,ios::out|ios::binary|ios::app);
char another[10];
do
{
cout<<"Please enter ID number :";
cin>>J.id;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"\nPlease enter first name: ";
cin.getline(J.fname,SIZE);
cout<<"\nPlease enter lastname: ";
cin.getline(J.lname,SIZE);
outfile.write((char*) &J, sizeof(J));
cout<<"Add another record:[Y]/[N] ";
cin.get(another[0]);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while(another[0]=='y'||another[0]=='Y');
cout<<"exiting to main menu.."<<endl;
}
//function
void delAll(char fname[])
{
fstream outfile;
cout<<"\n------------------\n"<<endl;
cout<<"\nDelete all records"<<fname<<"..."<<endl;
cout<<"\nAre you sure you want to delete all records in "<<fname<<" [Y]/[Any key for exit]?"<<endl;
char ch;
cin>>ch;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(ch=='y'||ch=='Y')
{
outfile.open(fname,ios::out|ios::binary|ios::trunc);
outfile.close();
}
else {cout<<"\nExiting to main menu..."<<endl;}
}
//function
void listAll(Rec&J,fstream &infile,char fname[])
{
infile.clear();
infile.open(fname,ios::in|ios::binary);
infile.read((char*)&J,sizeof(J));
cout<<"|=======================================================|"<<endl;
cout<<"| # | ID | FIRST | LAST |"<<endl;
cout<<"|=======================================================|"<<endl;
int count=1;
while(!infile.eof())
{
cout<<"| "<<setw(6)<<left<<count<<left<<"| "<<setw(9)<<J.id<<"| ";
cout<<left<<setw(14)<<J.fname<<"| ";
cout<<left<<setw(19)<<J.lname<<"|"<<endl;
infile.read((char*)&J,sizeof(J));
count=count+1;
cout<<"|-------------------------------------------------------|"<<endl;
}
infile.close();
}
//function
void appRec(Rec &J,fstream &outfile, char fname[])
{
outfile.open(fname,ios::out|ios::binary|ios::app);
outfile.clear();
cout<<"Please enter ID number :";
cin>>J.id;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"\nPlease enter first name: ";
cin.getline(J.fname,SIZE);
cout<<"\nPlease enter lastname: ";
cin.getline(J.lname,SIZE);
outfile.write((char*) &J, sizeof(J));
outfile.close();
}
//----------------------------------------------------
void delRec(Rec&s,fstream &infile, fstream &outfile,char fname[],char tname[])
{
int current, request=1;
infile.open("c:/solident.dat",ios::in|ios::out|ios::binary);
if (!infile.is_open())
cout << "infile not open\n";
outfile.open("c:/temp.dat",ios::out|ios::binary|ios::trunc);
if (!outfile.is_open())
cout << "outfile not open\n";
for (;;)
{
infile.read((char*)&s, sizeof s);
if (infile.eof())
break;
current = s.id;
if (current != request)
outfile.write((char*)&s, sizeof s);
}
infile.close();
outfile.close();
infile.open("c:/temp.dat)",ios::in|ios::binary);
outfile.open("c:/solident.dat)", ios::out|ios::binary|ios::trunc);
for (;;)
{
infile.read((char*)&s, sizeof (s));
if (infile.eof())
break;
outfile.write((char*)&s, sizeof (s));
}
infile.close();
outfile.close();
}
void srcRec(Rec&Job,fstream &infile,char fname[])
{
cout << "Allowing the user to open a specific record.\n";
infile.open(fname, ios::in | ios::binary) ;
if(infile.fail())
{
cout << "Could not access file.\n";
}
else
{
int position; //user's position
//gets user's position
cout << "Please the record you would like to read: ";
cin >> position;
//ignore luki
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//find the specific record, read it, and display it
infile.seekp((position - 1)*sizeof(Job));
infile.read((char*) &Job, sizeof(Job));
cout<<"|===============================================|"<<endl;
cout<<"| ID | FIRST | LAST |"<<endl;
cout<<"|===============================================|"<<endl;
cout<<left<<"| "<<setw(9)<<Job.id<<"| ";
cout<<left<<setw(14)<<Job.fname<<"| ";
cout<<left<<setw(19)<<Job.lname<<"|"<<endl;
}
//clears and closes the file
infile.clear();
infile.close();
}
void modRec(Rec &J,fstream &outfile, char fname[])
{
int position, //user's position
cntr = 0; //marks the current record within the file
cout << "Modifying a record.\n";
//open the two files
outfile.open(fname, ios::out | ios::in | ios::binary);
//get the user's desired position
cout << "please enter the record you would like to modify: ";
cin >> position;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl;
if(outfile.fail())
{
cout << "File could not be read.\n";
}
else
{
//find the desired record
outfile.seekp((position - 1)*(sizeof(J)));
//get the user's modification
cout<<"Please enter ID number :";
cin>>J.id;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"\nPlease enter first name: ";
cin.getline(J.fname,SIZE);
cout<<"\nPlease enter lastname: ";
cin.getline(J.lname,SIZE);
//write over the desired record
outfile.write((char*) &J, sizeof(J));
}
//closes the files
outfile.close();
}
void sort()
{
int StructureSize, Idx1, Idx2;
FILE * binaryFile;
binaryFile = fopen("c:/solident.dat","rb+");
Rec Index, IndexTemp;
StructureSize = sizeof(Index);
fseek(binaryFile, 0, SEEK_END);
int fileSize = ftell(binaryFile);
rewind(binaryFile);
for (Idx1 = 0; Idx1 < fileSize; Idx1 += StructureSize)
{
for (Idx2 = 0; Idx2 < fileSize - StructureSize; Idx2 += StructureSize)
{
fread(&Index, StructureSize, 1, binaryFile);
fread(&IndexTemp, StructureSize, 1, binaryFile);
if (Index.id > IndexTemp.id)
{
fseek(binaryFile, -(StructureSize * 2), SEEK_CUR);
fwrite(&IndexTemp, StructureSize, 1, binaryFile);
fwrite(&Index, StructureSize, 1, binaryFile);
fseek(binaryFile, -StructureSize, SEEK_CUR);
}
else
{
fseek(binaryFile, -StructureSize, SEEK_CUR);
}
}
rewind(binaryFile);
}
fclose(binaryFile);
}
I don't know, there seem to be a few issues with this code. Here's just one of them though
int request=1,current;
...
while (!infile.eof())
{
s.id=current;
if (current!=request)
At no point in this code do you give current a value, but you are still using the variable. This is an uninitialised variable which is one reason your code isn't working.
I wonder if you meant to write
current=s.id;
instead? That would make a little more sense.
Try reading the file with a loop like this
infile.open("c:/solident.dat",ios::in|ios::out|ios::binary);
if (!infile.is_open())
cout << "infile not open\n";
outfile.open("c:/temp.dat",ios::out|ios::binary|ios::trunc);
if (!outfile.is_open())
cout << "outfile not open\n";
for (;;)
{
infile.read((char*)&s, sizeof s);
if (infile.eof())
break;
current = s.id;
if (current != request)
outfile.write((char*)&s, sizeof s);
}
infile.close();
outfile.close();
I wouldn't use fail() if I were you. I think it's extremely unlikely you'll detect a genuine read or write failure with it. It's much more likely to be an end of file error, or a failure to open a file.
#john .Thanks!
The first part works, but trying
rename(tempname,destination) does not work:
(the dest file exists)
Although the file temp.dat now contains the records minus the one deleted , the output is not written to the solident.dat file(it remains unchanged)
//So I tried to read every rec from file and write every record to dest file:
infile.open("c:/temp.dat)",ios::in|ios::binary);
outfile.open("c:/solident.dat)", ios::out|ios::binary|ios::trunc);
infile.read((char*)&s, sizeof s);
for (;;)
{
if (infile.eof())
break;
infile.read((char *)&s, sizeof (s));
outfile.write((char*)&s, sizeof (s));
}
infile.close();
outfile.close();
My understanding was, that outfile and infile are pretty straightforward: fstream.open, close , clear and it should work (I thought). It seems though that I'm missing something essential, because the simple delete binary struct function in the program seems to be a hit and miss and I've been going around in circles for a few days: parts of it work, then I add a few lines of code and either a function fails or the whole program fails.I tend to blame it on the compiler or devc++ :) but I'm certain it has to be the code that is invalid!
Thanks for help!