Home > Enterprise >  Ofstream does create but doesn't write to file
Ofstream does create but doesn't write to file

Time:01-09

Here is the code:

void makefiles(char* filename) {
    ifstream file(filename, ios::in);

    // number of entries in main file 
    int size = 0;

    // names is the vector that holds entries 
    vector<string> names;
    string tmpstr;

    while (getline(file, tmpstr)) {
        string toadd = "";
        for (int i = 0; i < tmpstr.size(); i  ) {
            if (tmpstr[i] != '|')
                toadd  = tmpstr[i];
            else
                break;
        }
        if(count(names.begin(), names.end(), toadd) == 0)
            names.push_back(toadd);
        size  ;
    }
    file.close();

    ofstream userfile;
    file.open(filename, ios::in);
    for (int i = 0; i < names.size(); i  ) {
        userfile.open(string(getenv("TEMP"))   "\\"   names[i]   ".txt", ios::out);
        
        cout << string(getenv("TEMP"))   "\\"   names[i]   ".txt" << endl;
        
        while (getline(file, tmpstr)) {
            if (tmpstr.rfind(names[i], 0) == 0) {
                userfile << tmpstr << endl;
                userfile.flush();
            }
        }
        userfile.close();
    }

    file.close();


}

This function is being called from main, filename contains some formatted text, like email database of the next view:

[email protected]|[email protected]|06.01.2023|21:09:30|born in the abyss|156
[email protected]|[email protected]|06.01.2023|21:09:30|born in the abyss|156
[email protected]|[email protected]|23.12.2009|13:52:16|prikol|13
[email protected]|[email protected]|06.01.2023|21:09:30|aorn in the abyss|156

Thus, one line is one entry

In conclusion, I get many empty files that have the names i want, but, again, they are empty

I tried adding right after opening userfile:

if(!userfile){
    cout << "File is not opened" << endl;
    return;
}

But it doesn't help because !userfile = false

I tried instead of userfile << tmpstr << endl, using userfile << tmpstr << flush;

CodePudding user response:

You are writing at most one file. On the first iteration of the last for loop, with i==0, the inner while loop reads file all the way to EOF. On all subsequent iterations, file is already at EOF and all getline calls fail immediately. So all the files but the first (the one named after names[0]) are created but never written to.

  • Related