Writing to a CSV file type



  • HI,

    I'm trying to write a set of data to a CSV file in Qt 5.6 on a windows machine.

    So far I have

    // Save as a CSV file
    
    QString species;
    
    species = ui->tBSpecies->text();
    

    QFile file("./file.csv");
    if (file.open(QFile::WriteOnly|QFile::Truncate))
    {
    QTextStream stream(&file);
    stream << species << "\t" << gType << "\t" << species << "\t" << tSLen << "\t" << tSWidth << "\t" << tSThick << "\t"
    << tSMass << "\t" << den << "\t" << fLong << "\t" << fCross << "\t" << fDiag << "\t"
    << eLong << "\t" << eCross << "\t" << eDiag << "\t" << eG << "\t" << targetThick << "\n"; // this writes first line with two columns

    file.close();

    Most of the variables are doubles and come in from another function (species and gType are the only strings).

    The part I am having trouble with is looking at the CSV file to see if it already contains data and placing the new data in the first open row so that i do not overwrite existing data.

    Anything that points me in the right direction would be great.

    Thank you
    Steven



  • @Steven_DAntonio Hi!

    if it already contains data and placing the new data in the first open row

    Then why do you use QIODevice::Truncate? I think QIODevice::Append would be the right choice in this case.


  • Qt Champions 2016

    @Steven_DAntonio said:

    The part I am having trouble with is looking at the CSV file to see if it already contains data and placing the new data in the first open row so that i do not overwrite existing data.

    Are you trying to update rows that are already written? If so, you can't. CSV is a text file, so this won't work. If you only want to append, see @Wieland's suggestion.



  • HI,

    Thank you for the replies, it looks like the append function is just what I may be looking for. I'm not trying to change any values, in fact changing anything that is written previously is just what I want to avoid. What I'm looking to do is to keep the order (species (the first variable) is always saved to column 1 of the first available empty row, gType to the second etc.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.