Thursday, June 2, 2011

C++ File Read/Write at the same time

I ran into a problem where after I read a file using getline command, nothing was written to the file. You can overcome this problem using yourFile.clear(); yourFile.seekg(0).

sample code

    string zline;
    int iLine = 1;
    fstream m_File;

    m_File.open(zFileName, ios::in | ios::out | ios::app);
    if (true == m_File.is_open())
    {
        while (getline(m_File, zline))
        {
            ++iLine;
        }

        m_File.clear();
        m_File.seekg(0);

        m_File << iLine << " " << "Test" << "\n";
        m_File << flush;
        m_File.close();
}