Search code examples
c++qtdatetimeqfileqtextstream

Setting the name of a text file to a variable in qt


I'm exporting data to a text file in qt every time a run a code. With my current code that file is overwritten each time. My question is how can I set the title to be a variable eg pulse_freq, this way new files will be created based on my variable values. I just can't get the syntax right.

Is there a way to put my files in a folder in the same directory as my build files? I need my code to be cross platform and if I use the full path name it's apparently incompatible with any non-windows OS. If I just name the files there'd be too much clutter in the folder. Relevant code is below:

// Export to data file
        QString newname = QString::number(variables.nr_pulses);
        QString filename = "C:/Users/BIC User/Documents/BIC Placement Documents/QT_data/Data.txt";
        QFile file( filename );

Solution

  • You can just use something along lines:

    QString s1 = "something";
    QString s2 = " else";
    QString s3 = s1 + s2;
    

    QString concatenation with overloaded operator+ works like charm.

    And about referencing folder you're in, instead of hardcoding its path, use QDir::currentPath()

    Thus, your filename creation should look like the following:

    QString folder = QDir::currentPath();
    QString file = QString::number(variables.nr_pulses); //or whatever else you want it to be
    QString extension = ".txt" // or whatever extension you want it to be
    
    QString full_filename = folder + file + extension;
    

    In order not to mess with appending string after the extension, just separate it into another QString and concatenate those 3 elements as above (folder + file + extension).