2013-03-17 110 views
0

的代码是这样错误文件处理C++

ofstream f("bank.dat", ios::app); 
ifstream fa("bank.dat"); 
int n = 0, flag = 0; 
struct bac 
{ 
    char name[10]; 
    char amt[5]; 
} s; 

void add() 
{ 
    cout << "\nenter the details "; 
    cin >> s.name >> s.amt; 
    f.write((char *)&s, sizeof(bac)); 

} 

void ser() 
{ 
    ifstream fa("bank.dat"); 
    fa.seekg(0); 
    char x[10]; 
    cout << "\nenter value to be searched "; 
    cin >> x; 

    while (fa && flag == 0) 
    { 
     n++; 
     fa.read((char *)&s, sizeof(bac)); 
     if (strcmp(s.name, x) == 0) 
     { 
      flag = 1; 
      break; 
     } 
    } 
    if (flag == 1) 
    { 
     cout << "\nfound"; 
     cout << "\nAmount " << s.amt; 
    } 


} 

void mod() 
{ 
    ser(); 
    cout<<" "<<n; 
    if (flag == 1) 
    { 
     f.seekp((n - 1) * sizeof(bac)); 
    // cout<<f.tellp(); 
     cout<<"\nnew details "; 
     add(); 
    } 
} 


int main() 
{f.seekp(0); 
    int ch; 

     cout << "\nBANK MANAGEMENT SYSTEM \n"; 
     cout << "enter choice "; 
     cout << "\n1.add\n2.search\n3.delete and overwrite "; 
     cin >> ch; 
     if (ch == 1) 
     { 
      add(); 
     } 
     if (ch == 2) 
     { 
      ser(); 
     } 
     if (ch == 3) 
     { 
      mod(); 
     } 

    return 0; 
} 

我所要做的就是让与搜索,显示的程序和修改功能;

ERROR

记录被在最后追加,甚至当我使用

f.seekp((n - 1) * sizeof(bac)); 

操作来执行

*添加SID,特区命名为AMTS 5项,6分别为

*与名称替换命名条目SID:SID(同原始)AMT:7

文件

EXPECTED SID 7的输出SAR 6

FOUND SID 5 sar 6 sid 7

回答

1

我认为这是因为您使用的是ios :: app标志。

因为它是写here

app: (append) Set the stream's position indicator to the end of the stream before each output operation. 
+0

嗯,对了...但改变它为ios ::吃或把它留空,不会做伎俩! – 2013-03-17 13:36:33

+1

我想你必须保持空白,并将写入光标放在流的末尾,在'add'方法 – 2013-03-17 13:39:11

+0

thnx中,好吧,我会尝试 – 2013-03-17 13:52:44

1

在ser()操作开始时重新初始化'n = 0'。目前,每次调用搜索时都会继续增加'n',这就是记录被追加到文件尾部的原因。我建议不要使用全局变量'n'和'标志',而是返回这些值,例如

int ser() 
{ 
    // return n if search succeeds else return '-1'. 
} 

我看到它可以用各种方式改进,也许看看标准书中的IO示例代码。

+0

日Thnx你的建议,我会考虑它! – 2013-03-17 13:37:03