Read and Writing not working simultaneously
In this program i want to goto a particular location in the file and read
there.
If it is space there i will write my buffer there else i want to search
for the next "empty space". Now the problem is with those lines where I
have written in comments put 2 lines under comment from here. If I include
those lines my output file is blank. If I remove those 2 lines it is
writing correctly in the file. But I want to read before writing.
And by those 2 lines of code, I can read. So can you suggest me any
alternate way of reading so that buffer file goes into output file after
reading and not remains blank.
Or what am I doing wrong here?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//moving the seekp pointer of the fstream
void seek_key(fstream &fout,int k){
if(k==0)
fout.seekp(0,ios::beg);
else{
k=((k*2)-1)+(k*42);
fout.seekp(k,ios::beg);
}
}
//moving the seekg pointer of fstream
void seec_key(fstream &fout,int k){
if(k==0)
fout.seekg(0,ios::beg);
else{
k=((k*2)-1)+(k*42);
fout.seekg(k,ios::beg);
}
}
//to put n spaces in the file so that later i can put record in that location
//actually doing hashing files
void make_file(fstream &fout,int n){
int i;
i=n;
i--;
while(i>0){
for(int j=0;j<42;j++)
fout<<" ";
fout<<"\n";
i--;
}
}
struct student{
string roll;
string name;
string cgpa;
};
class buffer{
public:
string buf;
void pack(student s);
void unpack(istream fin,student s);
};
void buffer::pack(student s){
buf=s.roll;
buf=buf+"|";
buf=buf+s.name;
buf=buf+"|";
buf=buf+s.cgpa;
buf=buf+"|";
}
//cin overloading to get input into student structure
istream &operator >> (istream &in,student &s){
cout<<"enter student name: ";
in>>s.name;
cout<<"enter student roll: ";
in>>s.roll;
cout<<"enter cpga: ";
in>>s.cgpa;
}
//for adding student buffer into the file
void add(fstream &fout,buffer &b,student &s,int k){
int key=atoi(s.roll.c_str());
int v=key%k;
char test;
seek_key(fout,v);
seec_key(fout,v);
// put 2 lines under comments from here
fout>>test;
cout<<"this is test."<<test<<".test"<<endl;
fout<<b.buf;
}
int main(){
student s;
buffer b;
fstream fout;
fout.open("hash.txt");
int n;
cout<<"enter the no. of records: ";
cin>>n;
make_file(fout,n);
char ans;
do{
cin>>s;
b.pack(s);
add(fout,b,s,n);
cout<<"to enter more students press y else n";
cin>>ans;
}while(ans=='y'||ans=='Y');
fout.close();
return 0;
}
No comments:
Post a Comment