微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 fstream 写入文件在 c++

如何解决使用 fstream 写入文件在 c++

我想在向文件写入内容之前进行一些检查。当我进行这些检查时,写作不起作用。这可能是什么原因?

检查过程是这样的。用户输入的数据是否在文件中? 如果有更简单的方法来检查这个,我也可以试试。

工作代码

void add_dealer(){
    file.open("center.txt",ios::out|ios::app);
    c.new_Dealer();
    file.write((char*)&c,sizeof(Center));
    file.close();
    cout << "The dealer has been saved.";
}

检查后:

fstream file;

bool check_dealer_name(string name){
    bool result = false;
    file.open("center.txt",ios::in);
    while(file.read((char*)&c,sizeof(Center))){
        if(c.getLocation()== name){
            result = true;
        }
    }
    return result;
}
bool check_dealer_id(int id){
    bool result = false;
    while(file.read((char*)&c,sizeof(Center))){
        if(c.getID() == id){
            result = true;
        }
    }
    return result;
}
void add_dealer(){
    c.new_Dealer();
    file.open("center.txt",ios::out|ios::app);
    if (!check_dealer_id(c.getID()) || !check_dealer_name(c.getLocation())){
        file.write((char*)&c,sizeof(Center));
        file.close();
        cout << "The dealer has been saved.";
    }
    else{
        cout << "This Dealer name or dealer id already exists" << endl;
    }
    file.close();

}

类:

class Center{
    int ID;
    char location[50];
public:
    void new_Dealer(){
        cout << "Enter the Dealer ID: " ;
        cin >> ID; 
        cout << endl << "Enter the Dealer location: ";
        cin >> location;
    }

解决方法

问题是您在检查后未能关闭文件。您无法使用已打开文件的变量打开文件。

此错误仅在您出于不同目的重复使用相同的 file 变量时才可能发生。我强烈建议您在需要使用它的每个方法中单独声明文件变量。这样,fstream 析构函数将在函数结束时自动关闭文件,您所犯的错误将是不可能的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。