Qt file directory operations QDir, QFile, QTemporaryDir/File, QTextStream, QDataStream, QSettings, QFileInfo, QFileSystemWatch

Abstract:

This Qt blog post mainly introduces which classes can be used when processing file directory operations in Qt development, what are the functions of these classes, how to use them roughly, common class methods of classes and related matters that need to be paid attention to. Wait, for more details, you need to search and read the official help document according to the class name.

QT provides the following classes related to file and directory operations:

  • QDir: class provides operations such as modifying, adding, deleting, and accessing the directory structure and its content files;

  • QFile: Open files, delete files, copy files, and can also modify file contents with other classes;

  • QTemporaryDir, QTemporaryFile: used to create temporary directories and temporary files;

  • QTextStream: The text stream class can conveniently read and write IO devices. This article mainly introduces its reading and writing of text files such as .txt;

  • QDataStream: The binary stream class provides the ability to read and write binary data. This article mainly introduces its ability to read and write binary files such as .dat;

  • QSettings: configure the creation, reading, and writing operations of .ini files;

  • QFileInfo: used to extract file information, including path, file name, suffix, etc.;

  • QFileSystemWatcher: Provides an interface for monitoring files and directories, such as the addition, deletion and other changes of files in the directory, and file modification changes;

Development environment: Qt5.14.1, Qt Creator 4.11.1

Keywords: Qt, file directory operation, summary, QDir, QTemporaryDir, QFile, QTemporaryFile, QTextStream, QDataStream, QFileInfo, QFileSystemWatcher

Statement: The author of this article is original. Please attach the source of the article and the link to this article when reprinting.

Article directory

      • Summary:
      • text:
        • QDir
          • Commonly used member functions:
          • Usage example:
        • QFile
          • Commonly used member functions:
          • Usage example:
        • QTemporaryDir, QTemporaryFile
          • QTemporaryDir
            • Commonly used member functions:
            • Usage example:
          • QTemporaryFile
            • Commonly used member functions:
            • Usage example:
        • QTextStream
            • Commonly used member functions:
            • Usage example:
        • QDataStream
            • Commonly used member functions:
            • Usage example:
        • QSettings
            • Commonly used member functions:
            • Usage example
        • QFileInfo:
            • Commonly used member functions:
            • Usage examples
        • QFileSystemWatcher:
            • Commonly used member functions:
            • Usage examples
      • Recommended reading:

Text:

QDir

QDir is a class in the Qt framework for handling files and directories. It provides a series of methods for obtaining directory contents, manipulating files and directories, and performing various file system operations.

Commonly used member functions:
  • exists(): Determine whether the directory exists.
  • currentPath(): Get the current working directory.
  • setPath(): Set the directory path.
  • dirName(): Get the directory name.
  • entryList(): Get the list of files and subdirectories in the directory.
  • mkdir(): Create a directory.
  • rmdir(): Delete a directory.
  • remove(): Delete files.
Usage example:
qDebug() << QStringLiteral("Application startup path:") + QCoreApplication::applicationDirPath() << endl; // Consistent with the Executable path set by the run

QDir dir("example"); // Default is under the path QCoreApplication::applicationDirPath()
if (!dir.exists())
    qWarning("Cannot find the example directory");
else
    qWarning("Succee find the example directory");

//Create directories and files
dir.mkdir("tmp"); // Create a new directory tmp under the dir path
if (!dir.cd("tmp")) // .../example/tmp exists() after splicing
    qWarning("Cannot find the tmp in directory");
else
{<!-- -->
    QFile file(dir.filePath("test.txt")); // ".../tmp/test.txt"
    if (!file.open(QIODevice::ReadWrite))
        qWarning("Cannot create the file %s", file.fileName());
}

// Get information about the files in the directory and arrange them from small to large
QDir dirLocal;
dirLocal.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
dirLocal.setSorting(QDir::Size | QDir::Reversed);

QFileInfoList list = dirLocal.entryInfoList();
qDebug() << "Bytes Filename";
for (int i = 0; i < list.size(); + + i)
{<!-- -->
    QFileInfo fileInfo = list.at(i);
    qDebug() << QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName());
}
QFile

QFile is an I/O device used to read and write text files, binary files and resources. A QFile can be used alone to read and write directly through the IODevice read and write function, but usually QTextStream or QDataStream is used to read and write data, and the file is read and written using the stream method.

Commonly used member functions:
  • exists(): Determine whether the file exists.
  • remove(): Delete files.
  • copy(): Copy the file contents to a new file.
  • open(): Open the file using the set OpenMode mode.
  • close(): Close the file after flush().
  • flush(): Flushes all buffered data to the file.
  • size(): Returns the size of the file.
  • pos(): Returns the position where data is written or read from the file, and the position of the file pointer.
  • seek(): Set the position of the file pointer.
  • read(): Read file data.
  • write(): Write data to the file.
Usage example:
//Create a QFile object and specify the file to be operated on QCoreApplication::applicationDirPath()
QFile file("demo.txt");
//Read and write files
if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
{<!-- -->
    qDebug()<<"File opening failed";
    return;
}
//Write two lines of string to the file
file.write("Mom, I want to eat roasted Sanyao\
");
file.write("Eat, eat big portions");
// Refresh the file data stream
file.flush();
file.seek(0);

// Go to one line in the file each time, and then output the read string
char * str = new char[88];
qint64 readNum = file.readLine(str,88);
// When there is an error in reading (return -1) or the number of characters read is 0, end reading
while((readNum !=0) & amp; & amp; (readNum != -1)){<!-- -->
    qDebug() << str;
    readNum = file.readLine(str,88);
}
file.close();
QTemporaryDir, QTemporaryFile
QTemporaryDir

In Qt development, sometimes you need to create a temporary directory to store some temporary files, and delete the directory after use. For example, you can create temporary data files in the temporary folder to perform some temporary data editing. For reading and writing, the directory is automatically deleted after the system work is completed, and the files disappear accordingly.

Commonly used member functions:
  • autoRemove(): Returns true if QTemporaryDir is in automatic removal mode.
  • errorString(): If isValid() returns false, this function returns error information.
  • filePath: Returns the pathname of the file in the temporary directory.
  • isValid(): Whether the temporary directory was successfully created.
  • path(): Returns the path to the temporary directory.
  • remove(): Delete the temporary directory.
  • setAutoRemove: Set the deletion mode of the temporary directory. The default is automatic deletion mode.
Usage example:
QTemporaryDir dirT;
if (!dirT.isValid()) // After creating the object, be sure to use isValid() to check whether the temporary directory is valid. Do not use exists()
{<!-- -->
    qDebug() << "Failed to create temporary directory:" << dirT.errorString();
    return;
}
QFile fileT(dirT.path() + "/Temporary.txt"); // Create Temporary.txt in the temporary directory
if(!fileT.open(QIODevice::ReadWrite | QIODevice::Text))
    qDebug()<<"File opening failed";

qDebug() << fileT.fileName();
// Read and write Temporary.txt data, which will automatically disappear after the work is completed.

fileT.close();
QTemporaryFile

Used to safely create unique temporary files. The file itself is created by calling open(). The name of the temporary file is guaranteed to be unique (i.e., guaranteed not to overwrite an existing file), and the file is subsequently deleted after the QTemporaryFile object is destroyed. This is an important technique to avoid data corruption for applications that store data in temporary files. The file name is automatically generated or created based on a template passed to the QTemporaryFile constructor.

Commonly used member functions:
  • setAutoRemove(): Sets whether temporary files are automatically deleted when closed. The default is true.
  • autoRemove(): Returns true if QTemporaryFile is in auto-remove mode.
  • open(): Open a temporary file for reading or writing.
  • fileName(): Get the path and file name of the temporary file.
  • fileTemplate(): Gets the template of a temporary file, which can be used to customize the naming of temporary files.
  • createNativeFile(): Creates a temporary file in the local file system.
Usage example:
QTemporaryFile tempFile; // Create a temporary file object
if(!tempFile.open())
{<!-- -->
    qDebug() << "Failed to create temporary file.";
    return;
}
// tempFile.setAutoRemove(false);

QTextStream filestream( & amp;tempFile); // Use QTextStream to write a temporary file
filestream.setCodec("UTF-8");
filestream << "Hello, World!"; // Write to temporary file
filestream.seek(0);

QString data;
data = filestream.readAll(); // Read the contents of the temporary file

tempFile.close(); // Close the temporary file. The temporary file will not be deleted at this time.

QString filePath = tempFile.fileName(); // Get the temporary file path and file name
qDebug() << "Temporary file path: " << filePath << data;
//The program ends and the temporary file is automatically deleted
QTextStream

When using Qt to read and write text files, Qfile is usually combined with QTextStream, because QTextStream can be read line by line, which is relatively convenient for processing data. The QTextStream class provides a convenient interface for reading and writing text files. Text files refer to files stored in plain text format, such as: .txt, .cpp, .html, .xml files, etc. are all plain text files. QTextStream can also be used in conjunction with IO device classes such as QBuffer, QTcpSocket, QUdpSocket, etc.

Commonly used member functions:
  • QTextStream(FILE *fileHandle, ): The constructor binds the file pointer.
  • readLine(): Reads a line of text from the stream and returns it as a QString.
  • readAll(): Read the entire contents of the stream and return it as a QString.
  • operator<<(): Write content to the QTextStream stream.
  • atEnd(): Determine whether the end of the file is reached
  • setAutoDetectUnicode(): Sets the QTextStream object to automatically recognize Unicode encoding.
Usage example:
//Input text stream
QFile filein("test.txt");
if(filein.open(QFile::WriteOnly | QFile::Truncate))
{<!-- -->
    QTextStream in( & amp;filein); // Create a writing stream
    in << 3.1415926; // Write data
    in << "Hello, World!";
}
filein.close();

/****************************************************** *****/

//Output file stream
QFile fileout("test.txt");
if(!fileout.open(QFile::ReadOnly | QIODevice::Text))
    qDebug() << fileout.errorString();
QTextStream out( & amp;fileout); // Create an output stream
while(!out.atEnd())
{<!-- -->
    QString oneLine = out.readLine(); // Read one line
    qDebug() << oneLine;
}
fileout.close();
QDataStream

Similar but different from QTextStream, QDataStream provides a convenient interface to read and write binary stream text .dat files. Broadly speaking, text, pictures, sounds, and videos can all be saved as ".dat" files. They will be stored in binary form in ".dat" files. QDataStream allows reading and writing binary data in specific formats, such as integers, floating point numbers, strings, etc. QDataStream can be used across platforms and supports most operating systems. and architecture.

Commonly used member functions:
  • QDataStream(QIODevice *d): The constructor binds the file pointer.
  • operator<<(): Write content to the QDataStream stream.
  • operator>>(): Read data from QDataStream
  • setVersion(): Set the data version of QDataStream.
  • setFloatingPointPrecision(): Set the precision of floating point numbers.
Usage example:
QFile DataFile("test.dat");
DataFile.open(QIODevice::ReadWrite); // Truncate and delete
QDataStream stream( & amp;DataFile);
stream << QString("sir this way"); //Input binary data
stream << (qint64)250;

DataFile.flush(); // It needs to be flushed, otherwise there will be no content.
DataFile.seek(0); // Also move the file pointer to the front

QString str;
qint64 num;
stream >> str >> num; // Read binary data
qDebug() << str << " | " << num;

DataFile.close(); // Although QFile will automatically close
QSettings

QSettings is used to read and write .ini files. .ini files are initialization files. In addition to windows, many application software under other operating systems also have .ini files, which are used to configure application software to meet the requirements of different users. .ini can be used to store software information, registry information, etc.

Commonly used member functions:
  • setValue(): Set the value of the setting key to value. If the key already exists, the previous value is overwritten.
  • value(): Returns the value of the set key. .
  • allKeys(): Returns a list of all keys (including subkeys) that can be read using the QSettings object.
  • remove(): Removes the setting key and any subsettings of the key.
  • contains(): Returns true if there is a setting named key; otherwise returns false.
Usage examples

.ini file format

[Section1 Name] ; Section
Key11=value11 ; Parameter (build = value) // Annotation method of .ini file
Key12=value12
    
[Section2 Name]
Key21=value21
Key22=value22
//Write to .ini file
QSettings *configWrite = new QSettings("config.ini", QSettings::IniFormat);
configWrite->setValue("ip/first", "192.168.0.1");//Write content to the ip section of the ini file, the first parameter under the ip section
configWrite->setValue("ip/second", "127.0.0.1"); // Existing sections and parameters are replaced with val. If they do not exist, new values are assigned.
configWrite->setValue("port/open", "8888");
//Delete pointer after writing is complete
delete configWrite;

//Read .ini file
QSettings *configRead = new QSettings("config.ini", QSettings::IniFormat);
QString ipResult = configRead->value("/ip/second").toString();
QString portResult = configRead->value("/port/open").toString();
qDebug() << ipResult;
qDebug() << portResult;

//delete key
configRead->remove("/ip/first");
// Output all keys
QStringList keylist = configRead->allKeys();
qDebug() << keylist;
//Delete pointer after reading is complete
delete configRead;
QFileInfo:

The QFileInfo class provides us with system-independent file information, including the name of the file and its location in the file system, the access permissions of the file, whether it is a directory or a link, etc. Moreover, through this class, you can modify the file size and last modified and read time. At the same time, the QFileInfo class can also be used to obtain relevant information about Qt resources.

Commonly used member functions:
  • exists(), size(), absoluteFilePath(): file status information, existence, size, path.
  • isFile(), isDir(), isSymLink(): file type information, whether it is a file, folder, or symbolic link.
  • isReadable(), isWritable(), isExecutable(): File permission information, readable, writable, and executable.
Usage examples
QFileInfo fileInfo("demo.txt"); // It can be a path name or a pointer to QFile or QDir
qDebug() << "Size:" << fileInfo.size();
qDebug() << "Path:" << fileInfo.absoluteFilePath();

qDebug() << "File?:" << fileInfo.isFile();
qDebug() << "Folder?:" << fileInfo.isDir();

qDebug() << "Readable?:" << fileInfo.isReadable();
qDebug() << "Writable?:" << fileInfo.isWritable();
qDebug() << "Executable?:" << fileInfo.isExecutable();
QFileSystemWatcher:

QFileSystemWatcher monitors changes to files and directories in the file system by watching a list of specified paths.

Commonly used member functions:
  • addPath(): Adds a path to the file system watcher if the path exists.
  • files(): Returns a list of paths to files being monitored.
  • directories(): Returns a list of paths to the directories being monitored.
  • removePath(): Removes the specified path from the file system monitor.
  • directoryChanged(), fileChanged(): The signal function sent when the folder or file changes.
Usage examples
QFileSystemWatcher watcher;
watcher.addPath("demo.txt"); // monitoring file
watcher.addPath("example"); // monitoring directory
qDebug() << watcher.files() << endl << watcher.directories();

/****************************************************** ***************/

connect( & amp;watcher, SIGNAL(fileChanged(const QString & amp;)), this, SLOT());
connect( & amp;watcher, SIGNAL(directoryChanged(const QString & amp;)), this, SLOT());

over~

Recommended reading:

https://blog.csdn.net/weixin_45068267