Can’t write on a file after I pass its fstream to another class method

  c++, file

Here’s the code:

bool Universita::aggiungiStudenti(std::ifstream& file_studenti_da_inserire, bool database_creato, std::fstream& database) {
    Studente studente;
    std::string riga_file;
    std::vector<std::string> parsing;
        
    while(std::getline(file_studenti_da_inserire, riga_file, 'n')) {            
        std::string matricola = Universita::getID(database, database_creato, 's');
        parsing = parsing_studenti(riga_file);
        database.seekp(0, std::ios_base::end);
        database << 'n' << matricola << ';' << parsing[0] << ';' << parsing[1] << ';' << parsing[2];
    }
}

If I try to write to database file before I call Universita::getID there aren’t any problems.
But if I try to do it after the call, nothing is written.

Here’s the code for Universita::getID:

std::string Universita::getID(std::fstream& database, bool database_creato, char tipo_ID) {
    std::string matricola = "ERRORE";
    std::string temp = "ERRORE";
    std::string riga_file = "ERRORE";
    int numero_matricola = 0;
    size_t size,resize = 0;
    
    bool last_line = false;
    //controllo se il file è vuoto o se è stato appena creato
    if((database.peek() == std::fstream::traits_type::eof()) || database_creato) {
        switch(tipo_ID) {
            case 's':
                matricola = "s000001";
                return matricola;
            case 'd':
                matricola = "d000001";
                return matricola;
            default:
                std::cerr << "Errore inserimento parametri funzione getUltimoID" << std::endl;
                break;
        }
    }
    
    database.seekg(-1, std::ios_base::end); //raggiungo la fine del file
    bool ricerca = true;
    while(ricerca) {
        char temp_char;
        database.get(temp_char);
    
        if((int)database.tellg() <= 1) {
            database.seekg(0);
            ricerca = false;
        } else if (temp_char == 'n') {
            ricerca = false;
        } else {
            database.seekg(-2, std::ios_base::cur);
        }
   }
    
    std::getline(database, riga_file);
    //elimino il primo carattere della matricola:
    temp = parsing_studenti(riga_file)[0];
    temp.erase(temp.begin());
    numero_matricola = stoi(temp, nullptr, 0);
    numero_matricola += 1;
    matricola = "000000" + std::to_string(numero_matricola);
    size = matricola.size();
    if(size > 6) {
        resize = size - 6;
        matricola.erase(0,resize);
    }
    return matricola;
}

Sorry for the name of variables and method which aren’t in English.

Source: Windows Questions C++

LEAVE A COMMENT