在这个程序中,我想转到文件中的特定位置并在那里阅读。
如果是空间,我会在那里写我的缓冲区,我想搜索下一个“空白空间”。现在问题在于我在评论put 2 lines under comment from 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;
}
答案 0 :(得分:0)
基本上,你有这个代码:
fout>>test; // line 1
// code not using fout removed
fout<<b.buf; // line 2
基本上,这意味着你在没有干预寻求的情况下进行阅读和写作:这是未定义的行为!文件流的状态可以由状态机描述:
initial -> unbound
unbound + write -> write mode
write mode + write -> write mode
write mode + seek -> unbound
write mode + read -> undefined behavior
unbound + read -> read mode
read mode + read -> read mode
read mode + seek -> unbound
read mode + write -> undefined behavior
有几个原因导致在写入模式下读取或以读取模式写入时未定义的行为:
无论如何:寻找你真正想要写数据的适当位置应该可以解决问题。