how to read and write to a file in qt c++
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
// Create a QFile object to work with a file named "example.txt"
QFile file("example.txt");
// Check if the file can be opened in WriteOnly and Text mode
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Could not open the file for writing";
return -1;
}
// Create a QTextStream object and associate it with the file
QTextStream out(&file);
// Write data to the file using QTextStream
out << "Hello, this is a sample text.\n";
out << "This is another line of text.";
// Close the file
file.close();
// Open the file for reading
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Could not open the file for reading";
return -1;
}
// Read data from the file line by line and output to console
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
qDebug() << line;
}
// Close the file
file.close();
return a.exec();
}
Explanation:
#include
directives: Include necessary headers for working with Qt functionalities.QCoreApplication
: The entry point for Qt-based applications.QFile file("example.txt")
: Create a QFile object namedfile
and associate it with a file named "example.txt".if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
: Check if the file can be opened in WriteOnly and Text mode. If it fails to open, print an error message and return -1.QTextStream out(&file)
: Create a QTextStream object namedout
and associate it with thefile
for writing data to the file.Writing data to the file using QTextStream (
out << "Hello, this is a sample text.\n"; out << "This is another line of text.";
).file.close()
: Close the file after writing.Reopen the file for reading (
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
) and handle errors if it fails to open.QTextStream in(&file)
: Create a QTextStream object namedin
and associate it with thefile
for reading data from the file.Reading data from the file line by line using
while (!in.atEnd())
and outputting each line to the console usingqDebug() << line
.file.close()
: Close the file after reading.return a.exec()
: Return the result of the application's event loop execution (required for Qt applications).