【问题标题】:writing files with fstream doesnt work in c++用 fstream 写文件在 C++ 中不起作用
【发布时间】:2021-01-30 12:10:42
【问题描述】:

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

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

工作代码:

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;
    }

【问题讨论】:

  • 不能像这样读写对象,必须序列化和反序列化。
  • @spectras 这不是真的。看类定义,二进制读写完全没问题。
  • @john> 我读得有点快,确实那个特定的类应该可以工作。不过,这样很容易得到不可用的文件。

标签: c++ file writing


【解决方案1】:

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

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

【讨论】:

  • 你能用代码解释一下吗?我无法理解
  • @ZengaHivo 为了向您展示一些代码,我需要查看您调用 check_dealer_namecheck_dealer_id 的代码。
  • @ZengaHivo 但这里是快速解释。当您检查经销商时,您正在阅读文件。然后你在写文件的地方调用add_dealer。在这两者之间您必须关闭文件file.close(),如果您在两种情况下使用相同的变量,则无法打开已经打开的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
相关资源
最近更新 更多