Search code examples
c++fileloopsfilestreamofstream

C++ Writing a file inside a loop


This should be counting 30 seconds down into a txt file. But it hardly ever makes the txt itself either. What am I doing wrong? Or is it that in loop c++ is just not capable of file handling. There is just nothing in the text file

for (i = 30; i >= 0; i--)
    {
        ofstream file;
        file.open("asd.txt");
        file << i;
        file.close();
        Sleep(1000);
    }

Solution

  • Move the ofstream out of the loop like this :

    // ^^ There is the useless stuff
    ofstream file;
    for (i=0;i<maxs;i++)
    {
        system("cls");
        secondsLeft=maxs-i;
        hours=secondsLeft/3600;
        secondsLeft=secondsLeft-hours*3600;
        minutes=secondsLeft/60;
        secondsLeft=secondsLeft-minutes*60;
        seconds=secondsLeft;
        cout << hours<< " : " << minutes<< " : " << seconds << " ";
        file.open ("countdown.txt", ios::trunc);
        file << hours << " : "  << minutes<< " : " << seconds;
        file.close();
        Sleep(1000);
    }