Hi folks, I have written code to random access files in c++ . I got result without creating a method for write a record to the file. I have given the code snippet below.
But now i created a method inside the class to write and read the record. This is time i could not write and read successfully. What is the problem here. Please tell me.Code:#include<iostream> #include<fstream> #include<iomanip> using namespace std; class student { int rollno,marks; char name[20]; fstream fpointer; public: void show(); void get(); }; void student::get() { cout<<"Enter the name of student:"; cin>>name; cout<<"Enter the roll no. of student:"; cin>>rollno; cout<<"Enter the marks of student:"; cin>>marks; } int main() { student record; fstream file; file.open("student.txt",ios::in|ios::out|ios::binary|ios::app); char flag='y'; int i=0; while(flag=='y'||flag=='Y') { record.get(); file.seekp(i*sizeof(record), ios::beg); file.write((char*)&record,sizeof record); cout<<"Enter another record(Y/N)...."; cin>>flag; i++; } //file.seekg(0); cout<<"Roll No.\tName\tMarks"<<endl; file.seekp(2*sizeof(record), ios::beg); while(file.read((char*)&record,sizeof record)) { record.show(); } file.close(); return 0; } void student::show() { cout<<rollno<<"\t\t"<<name<<"\t"<<marks<<endl; }
Code:#include<iostream> #include<fstream> #include<iomanip> using namespace std; class student { int rollno,marks; char name[20]; public: void show(); void get(); int write(const student &,fstream &,int); int read(const student &,fstream &,int); }; void student::get() { cout<<"Enter the name of student:"; cin>>name; cout<<"Enter the roll no. of student:"; cin>>rollno; cout<<"Enter the marks of student:"; cin>>marks; } int student::write(const student &s,fstream &fp,int RecNum) { if( fp.seekp(RecNum*sizeof(s), ios::beg) == 0 ) if(fp.write((char*)&s,sizeof s)) return 1; return 0; } int student::read(const student &s,fstream &fp,int RecNum) { if( fp.seekg(RecNum*sizeof(s), ios::beg) == 0 ) if(fp.read((char*)&s,sizeof s)) return 1; return 0; } int main() { student record; fstream file; file.open("student.txt",ios::in|ios::out|ios::binary|ios::app); char flag='y'; int i=0; record.get(); record.write(record,file,2); cout<<"Roll No.\tName\tMarks"<<endl; record.read(record,file,2); file.close(); return 0; } void student::show() { cout<<rollno<<"\t\t"<<name<<"\t"<<marks<<endl; }



LinkBack URL
About LinkBacks



