2013-11-23 117 views
-1

我试图从文件中删除一个内容 到目前为止,我已经达到了将所有数据删除到另一个临时文件的想法,然后删除最老的重命名临时 这里是我的代码:有些东西不能正常工作

string username; 
       cout << "Enter The Employee you want to Remove : "; 
       cin >> username; 
       int i=0; 
       string line1,line2,line3; 
       fstream myfile; 
       fstream temp; 
       myfile.open("Data.txt"); 
       temp.open("temp.txt"); 
       if (myfile.is_open() || temp.is_open()) 
       { 
        while (myfile >> line1 >> line2 >> line3) 
        { 
         if(line1!="Employee" || username!=line2) 
         { 
          temp << line1 << endl << line2 << endl << line3 << endl; 
          continue; 
         } 
         else if (line1=="Employee" && username==line2) 
         { 
          i=1; 
         } 
        } 
        myfile.clear(); 
        myfile.seekg(0, ios::beg); 
        myfile.close(); 
        temp.close(); 
        remove("Date.txt"); 
        rename("temp.txt","Date.txt"); 
        if(i==0) 
        { 
         cout << "There is no Employee with The Name you Entered!" << endl; 
        } 
        else 
        { 
         cout << "Employee data has been Deleted." << endl; 
        } 
       } 

我跟踪的代码我的自我,它不创建临时文件! ,我可以使用这种技术来进行更新吗?

+0

看起来像我手动创建它运行的临时文件 但它并没有删除最古老的! –

回答

0

阅读这样的代码真的很难......但是,我会给它一个镜头。

你为什么要使用

(myfile.is_open() || temp.is_open()) 

的条件?你不应该核实这两个文件是开放的,因此正在

(myfile.is_open() && temp.is_open()) 

我在问,因为可能你的sw没有打开临时文件,可能是因为你没有从操作系统的文件夹写入权限,但仍然通过OR条件测试继续。

但这是一个疯狂的猜测。

+0

我改进了帖子,对不起4 回答你的问题,当我&&它不会从第一个地方输入if条件:/ –