Search code examples
c++csvread-write

Trying to read AND THEN write on csv file


I'm trying to read something from a file and then write in the same file. I had something like this and worked wonders:

int main() {

    fstream fp;

    string filePath = "test.csv";
    string outString;

    outString += "g1;1901;3;3;4;3;3;3;3\n";
    outString += ";1902;3;3;4;3;3;3;3\n";

    fp.open(filePath, ios::app | ios::in | ios::out);
    fp << outString;
    fp.close();
    return 0;
}

then I had the read part, it reads well but then it doesn't write:

int main() {

    fstream fp;
    string outString;
    string filePath = "test.csv";


    string line, csvItem;
    int numberOfGames = 0;

    fp.open(filePath, ios::app | ios::in | ios::out);
    if (fp.is_open()) {
        while (getline(fp, line)) {
            istringstream myline(line);
            while (getline(myline, csvItem, ';')) {
                cout << csvItem << endl;
                if (csvItem != "" && csvItem.at(0) == 'g') {
                    numberOfGames++;
                }
                else
                    break;
            }
        }
    }

    if (numberOfGames == 0) {
        outString = "Game;Year;AUS;ENG;FRA;GER;ITA;RUS;TUR\n";
    }

    outString += "g";
    outString += to_string(numberOfGames + 1);
    outString += ";1901;3;3;4;3;3;3;3\n";
    outString += ";1902;3;3;4;3;3;3;3\n";

    fp << outString;

    fp.close();


    return 0;
}

The file is created if it doesn't exist, else, it is read. The read part was based on the accepted answer to this question: Reading a particular line in a csv file in C++.

Thank you very much!


Solution

  • Once you reach the end of the file, you get fp.eof() == true. If you check the values returned by fp.tellg() (read/get position) and fp.tellp() (write/put position), you can see that they are invalid at that moment.

    What you need is to reset the stream state once you reach EOF and before you start reading:

    fp.clear();