QDir and QFile with Qt GUI C++
In this article, I will explain the QFile and QDir class operations with QT GUI C ++. With QFile, we do file read and write operations. Thanks to these operations, we can keep the values in the external files and use them in the program. In this way, we create a simple database.First we include the QFile object in the Header file in our program. That's how we do it.
#include "qfile.h"
#include "qdir.h"
Now let's first check if there is a folder. If there are no folders, let's create
For this we will create a QDir object and call it with its exist() function. The word Dir comes from the word Directory. Now let's go to our code…
QDir folder("c:/my_folder/");
if(!folder.exists())
{
QDir().mkdir("c:/my_folder/");
}
Here we checked the folder we were looking for with folder.exist (), and if not, we created it with mkdir(“”). This way you can check the files.
Now let's move on to reading and writing a file in QT GUI C ++.
First, let's print the file…
QFile file(“c:/my_folder/file.txt”);
file.open(QIODevice::Truncate|QFile::WriteOnly);
//Method of the opening file
file.write("");
file.close(); //we are closing the file after writing.
Here we created a file with QFile and then decided how to open it. What we mean by opening is what we do with the file. With the QIDevice option we emptied its contents and said just write with QFile.
Then we write data with write command. And we've closed it with close(). Here we created a file and emptied the contents.
Now let's move on to reading data. This is a very simple process.
Again, first we create a file with QFile and give way to inside
QFile file("c:/my_folder/file.txt"); //we have created the file
QTextStream text(&file); // we have read the file
while(!text.atEnd()) {
QString text_line= text.readLine();
ui->txtVeri->append(text_line);
}
//Here we have write the text from the file to the textbox
file.close();//and closed the read file
That is all.
Have a nice coding.
Burak Hamdi Tufan
Comments