Qt5 Tutorial QFile - 2020
In this tutorial, we will learn QFile.
The QFile class provides an interface for reading from and writing to files.
QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.
The file name is usually passed in the constructor, but it can be set at any time using setFileName(). QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.
We can check for a file's existence using exists(), and remove a file using remove().
QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system's local 8-bit encoding is used (e.g., UTF-8 on most unix based operating systems). This can be changed using setCodec().
To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right.
In the following code, we open a new file with the given name and write a text into the file. Then, we read in the file back and print the content to our console.
#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(); }
Output:
"QFile Tutorial"
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization