2011-10-31 83 views
0

嗨,我不能具体记录从我的二进制文件。这是列出所有记录的方法。C++中的随机访问文件

int student :: showall(fstream &fp) 
{ 
    student rec; 
    fp.seekg(0,ios::beg); 
    int i=0; 
    cout<<"Position\tRoll No\t\tName\tBalance"<<endl; 
    while(fp.read((char*)&rec,sizeof rec)) 
    { 
     cout<<i*sizeof rec<<"\t"; 
     rec.show(); 
     i++; 
    } 
} 

虽然运行此我得到了下面的输出

Position Roll No  Name Balance 0  1 
Heartly 10 28  2  
Heartly 20 56  3  
Heartly 30 84  4  
Heartly 40 112  5 
Heartly 50 140  6  
Heartly 60 168  7  
Heartly 70 196  8 
Heartly 80 224  9  
Heartly 90 252  10  
Heartly 100 

现在我要搜索特定的记录。我给了RecNo 5进行搜索。这是我的查看方法

int student :: view(fstream &fp,int RecNum) 
{ 
    student rec; 
    std::ios::pos_type SearchPosition = RecNum*sizeof rec; 
    cout<<endl<<"Position="<<SearchPosition<<endl; 
    if(fp.seekg(SearchPosition) == 0) 
    { 
     cout<<endl<<"Position="<<SearchPosition<<endl; 
      if(fp.read((char*)&rec,sizeof rec)) 
        rec.show(); 
     else 
      cout<<endl<<"Read Error .. ! "<<endl; 
     } 
    else 
    { 
     cout<<endl<<"Record Number Not Found"<<endl; 
    } 
} 

运行此方法后,我得到了下面的结果。

记录号(-1取消):5

位置= 140

记录号未找到

为什么它不定位特定记录?

printf("\nMenu : AddDummy, Add, View, Edit, List or Quit (U, A, V, E, L or Q) : "); switch(toupper(getchar())) {  
    case 'U' : 
     file.open("abc.cli",ios::in|ios::out|ios::binary|ios::app); 
      cout<<"Creating dummy file of 1000 entries"<<endl; 
      record.adddummy(file); 
     file.clear(); 
      break; 
    case 'A' : 
     file.open("abc.cli",ios::in|ios::out|ios::binary|ios::app); 
      record.get(); 
     record.add(record,file); 
      cout<<"Record Added"<<endl;   
      file.clear(); 
      break;    
    case 'E' :  
      file.open("abc.cli",ios::in|ios::out|ios::binary|ios::ate); 
      cout<<endl<<"Record number (-1 Cancels): "<<endl; 
      cin>>Rec; 
      if (Rec > -1){ 
       record.get(); 
     if(!record.update(record,file,Rec)) 
      cout<<"Record Edited"<<endl;    
      else 
      cout<<"Record Edited Failed"<<endl;  
     file.clear();} 
      break; 
    case 'V' :  
      file.open("abc.cli",ios::in|ios::out|ios::binary|ios::ate); 
      cout<<endl<<"Record number (-1 Cancels): "<<endl; 
      cin>>Rec; 
      if (Rec > -1) 
       record.view(file,Rec); 
     file.clear(); 
      break; 
    case 'L' : 
     file.open("abc.cli",ios::in|ios::out|ios::binary|ios::ate); 
      record.showall(file); 
     file.clear(); 
      break; 
    case 'Q' : 
      file.close(); 
     return 0; 
    default : 
     cout<<" \nNot Matching\n ";  
}while(getchar() != '\n'); 

为什么它不读书的具体记录?在这里输入的代码

+0

我试图格式化输入,我不认为我管理。你能进一步清理吗? – sehe

+0

你应该多读一点'seekg'方法,特别是它返回的内容。 –

回答

1

fstream::seekg返回fstream的参考,永远不会等于0,所以要检查的条件永远不会运行。 fstream::seekg

+0

非常感谢你!又一个问题?在switch语句中,如果我给出'L'列出,它首次列出所有。但是如果我再给'L'的意思,它没有列出任何东西?但是这个控制权被传递给showall方法。但它没有进入读取声明。为什么? – Heartly

+0

您正在重新打开文件,为什么?如果您重新打开该文件,失败位标志被设置为,您在之后创建的访问权限不正确。 –

+0

正确!感谢您的帮助!但我如何检查文件是否写入? – Heartly