Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to read and write to a file in qt c++

#include <QCoreApplication>
#include <QFile>
#include <QString>
#include <QDebug>
#include <QTextStream>

void write(QString filename)
{
    QFile file(filename);
    // Trying to open in WriteOnly and Text mode
    if(!file.open(QFile::WriteOnly |
                  QFile::Text))
    {
        qDebug() << " Could not open file for writing";
        return;
    }

    // To write text, we use operator<<(),
    // which is overloaded to take
    // a QTextStream on the left
    // and data types (including QString) on the right

    QTextStream out(&file;);
    out << "QFile Tutorial";
    file.flush();
    file.close();
}

void read(QString filename)
{
    QFile file(filename);
    if(!file.open(QFile::ReadOnly |
                  QFile::Text))
    {
        qDebug() << " Could not open the file for reading";
        return;
    }

    QTextStream in(&file;);
    QString myText = in.readAll();
    qDebug() << myText;

    file.close();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString filename = "C:/Qt/MyFile.txt";
    write(filename);
    read(filename);

    return a.exec();
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ rgb code 
Cpp :: 01matrix 
Cpp :: c++ How can I make a std::vector of function pointers 
Cpp :: #defie in c++ 
Cpp :: C:UsersBBCDocumentsc n c++ project8PuzzleSolvemain.c|38|warning: suggest parentheses around assignment used as truth value [-Wparentheses]| 
Cpp :: run a c++ file in terminal 
Cpp :: query for rmq using sqrt decomposition 
Cpp :: type defination in C++ 
Cpp :: decising how many numbers after comma c++ 
Cpp :: 7 9 C:UsersAliyahDocumentsshut up.cpp [Error] expected unqualified-id before string constant 
Cpp :: ue4 foreach loop c++ 
Cpp :: how to run c++ on cmd 
Cpp :: +++++++++ 
Cpp :: c++ vs c# 
Cpp :: show mouse c++ 
Cpp :: vector.rbegin() 
Cpp :: how to use and in c++ 
Cpp :: is vowel c++/c 
Cpp :: c++ Is there still a need to provide default constructors to use STL containers 
Cpp :: c++ login 
Cpp :: char * in c++ 
Cpp :: c++ is nan 
Cpp :: conditions in c++ 
Cpp :: are arrays faster than vectors c++ 
Cpp :: function overloading in cpp 
Cpp :: how to implement binders and decorators on c++ lik python? 
C :: Write a C program to print all unique elements in the array. 
C :: arduino serial read write structure 
C :: c code to python code converter online 
C :: prime numbers c 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =