Input and output, binary file
Apr 3, 2020 at 4:27am UTC
In this code i am not able to perform reading operation. In addition after writing data it itself assumes value of 'a' as ' ' and the loop ends.
Code written and compiled on Dev C++ 5.11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
// code to read and write binary file
#include<fstream>
#include<iostream>
using namespace std;
struct student
{
private :
int roll;
char name[10];
public :
void get_data()
{
cin>>roll;
cin.get(name,10);
}
void show_data()
{
cout<<name<<'\t' <<roll;
}
};
void write_data() //write in binary file
{
student s;
fstream f;
f.open("datesheet.dat" ,ios::binary | ios::app);
s.get_data();
f.write((char *)&s,sizeof (s));
f.close();
}
void read_data() //read from binary file
{
student h;
fstream f;
f.open("datesheet.dat" ,ios::binary | ios::in);
while (f.read((char *)&h,sizeof (h)))
{
h.show_data();
}
f.close();
}
int main()
{
int i;
char a;
x:
cout<<"You can perform following actions on the file: write(1)or read(2): " ;
cin>>i;
if (i==1)
{
write_data();
}
else if (i==2)
{
read_data();
}
else
{
cout<<"Wrong input!" ;
}
cout<<endl;
cout<<"Do you want to perform any operation again?(Y/N): " ; //loop to try again the process.
cin>>a;
if (a=='Y' || a=='y' )
{
goto x;
}
else if (a=='N' || a=='n' )
{
cout<<"Well Okay. Bye!!" ;
}
else
{
cout<<endl<<"*" <<a<<"*" <<endl; //to check that what is default value of 'a' as taken by program.
cout<<"I will take this as no." ;
}
return 0;
}
Apr 3, 2020 at 5:33am UTC
Topic archived. No new replies allowed.