'writing files with fstream doesnt work in c++

I want to do some checks before I write something to my file. Writing does not work when I make these checks. What could be the reason for this?

The checking process works like this. Is the data entered by the user in the file? If there is a simpler way to check this I can try that too.

Working code:

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

After doing the checking:

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:

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



Solution 1:[1]

The problem is that you fail to close the file after your checks. You can't open a file using a variable that already has the file open.

This error is only possible because you are reusing the same file variable for different purposes. I strongly recommend that you declare the file variable separately in each method that needs to use it. That way the fstream destructor will automatically close the file at the end of the function and the error you made would be impossible.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 john