Qt File Processing

Source: Internet
Author: User

Qt provides the qfile class for file processing. To make it easier to process text files or binary files, QT also provides the qtextstream class and qdatastream class. You can use qtemporaryfile to process temporary files, you can use qfileinfo to obtain file information.
To process the directory, you can use qdir. To monitor file and directory changes, you can use qfilesystemwatcher.

Read/write text files
The qfile class provides interfaces for reading and writing files. The qfile class can read and write text files, binary files, and QT resource files. You can also use the more convenient qtextstream and qdatastream class to read text files and binary files, to open a file, you can specify the file name in the constructor, or use the setfilename () function to set the file name at any time. To open the file, use the open function to close the file and use the close function. In qfile, you can use the Readline () function inherited by qiodevice to read and write a row of text files. For example:
Qfile file ("zeki.txt ");
If (file. Open (qiodevice: readonly ))
{
Char buffer [2048];
Qint 64 linelen = file. Readline (buffer, sizeof (buffer ));
If (linelen! =-1)
{
Qdebug <}
}
If the read succeeds, Readline returns the actual number of bytes read. If the read fails,-1 is returned.
Qtextstream provides more convenient interfaces to read and write text. qtextstream can operate qiodevice, qbytearray, and qstring. qtextstream using stream operators to conveniently read and write words, rows, and numbers. To generate text, qtextstream provides formatting options for filling, alignment, and number formatting. For example
Qfile data ("test.txt ");
If (data. Open (qfile: writeonly | qfile: truncate ))
{
Qtextstream out (& data );
Out <}

Formatting Function of qtextstream
----------------------------------------------
Qsetfieldwidth (INT width) to set the field width
Qsetpadchar (qchar ch)
Qsetrealnumberprecision (INT precision)
----------------------------------------------
The default encoding used in QTextStream is the encoding returned by the QTextCodec: codecForLocal () function, and Unicode can be detected automatically. You can also use the stream encoding set by the QTextStream: setCodec (QTextCodec * codec) function.

Operate binary files
The QDataStream class provides the ability to serialize binary files. QDataStream serializes the c ++ basic data types, such as char, short, int char * more complex data types are serialized by dividing the data types into basic data types. The following code is used to write binary data to the data stream.
QFile file ("binary. dat ");
File. open (QIODevice: WriteOnly );
QDataStream out (& file );
Out <(qint32) 42 <(qint32) 96;
The process of reading the file written above is as follows:
QFile file ("binary. dat ");
File. open (QIODevice: ReadOnly );
QDataStream in (& file );
QString str;
Qint32 x, y;
In> str> x> y;
Each entry can be defined to write files in binary format. Many types in Qt, including QBrush, QColor, QDateTime, QFont, QPixmap, QString, and QVariant, can be written to data streams.

To read the original data, you can use readRawData () to read the data to the pre-defined char * buffer and write the original data using writeData (). To read and write the original data, you must encode and decode the data.
The following example demonstrates the process of using qdatastream to read and write files.
# Include
# Include
Using namespace STD;
Int main (INT argc, char ** argv)
{
Qcoreapplication app (argc, argv );
Qfile file ("binary. File ");
File. Open (qiodevice: writeonly | qiodevice: truncate );
Qdatastream out (& file );
Out <out <(qint32) 21;
File. Close ();

File. setfilename ("binary. File ");
If (! Ifle. Open (qiodevice: readonly ))
{
Cout <"An error occurred while opening the file! ";
Return 1;
}
Qdatastream in (& file );
QString name;
QDate birthday;
Qint32 age;
In> name> birthday> age;
QDebug () <cout <qPrintable (birthday. toString ("yyyy MMMM dd dddd "));
File. close ();
Return 0;
}
In this example, the QDataStream class writes three data types: Name (QString), birthday (QDate), and age (qint32). The data is read in the same type. QDataStream can read data generated by any object generated using the QIODevice class. Data such as QTcpSocket, QUdpSocket, QBuffer, QFile, and QProcess. You can use QDataStream to write data at one end of QAbstractSocket, and use QDataStream to read data at the other end, which eliminates the hassle
High-end and low-end bytes conversion process.
Temporary Files
Temporary files may be used in practical applications. The QTemporaryFile class is provided in Qt to provide temporary files. QTemporayFile allows you to securely create a first, second, and second temporary file. Temporary files are created through open. Qt ensures that temporary files are not duplicated. After a temporary file object is destroyed, the temporary file is automatically deleted. The temporary file can be opened after it is closed through close (). As long as the temporary file object has not been destroyed, the temporary file will always exist and be opened internally by QTemporaryFile. The temporary directory of the system can be obtained through QDir: tempPath (). For unix/linux systems, the temporary directory/temp is usually specified by TEM/TMP on windows.

Directory operations and file management
The QDir class has the ability to access the directory structure and content. You can use QDir to operate directories, access directories or file information, operate on underlying file systems, and access Qt resource files. Qt uses/as the common directory delimiter and URL path separator. Qt can use relative paths and absolute paths to point to a file. The isRelative () and isAbsolute () functions can determine whether the QDir object uses relative paths or absolute paths. Use the makeAbsolute () function to convert relative paths to absolute paths. The directory path can be returned through the path () function. The setPath () function is used to set a new path. The absolute path is returned using absolutePath. You can use dirName () to return the directory name. The directory path can be changed through cd () cdUp (). You can use mkdir () to create a directory and rename () to change the directory name. To determine whether a directory exists, you can use exists (). You can use isReadable (), isAbsolute (), isRelative (), and isRoot () to obtain the directory attributes. There are many entries in the directory, including files, directories, and symbolic links. You can use count () to count the total number of entries. EntryList () returns a string linked list composed of all entries in the directory. You can use the remove () function to delete a file and rmdir () to delete the directory.
Linux du command

Int main (int argc, char ** argv)
{
QCoreApplication app (argc, argv );
Qstringlist ARGs = app. Arguments ();
Qstring path;
If (ARGs. Count ()> 1)
Path = ARGs [1];
Else
Path = qdir: currentpath ();
Qdebug () <du (PATH );
Return 0;
}
Qint64 du (const qstring & Path)
{
Qdir Dir (PATH );
Qint64 size = 0;
Foreach (qfileinfo fileinfo, dir. entryinfolist (qdir: Files ))
Size + = fileinfo. Size ();
Foreach (qstring subdir, dir. entrylist (qdir: dirs | qdir: nodotanddotdot ))
Size + = DU (path + dir: separator () + subdir );
Char unit = // 'B ///';
If (curSize & gt; 1024)
{
CurSize // = 1024;
Unit = // 'K ///';
If (curSize & gt; 1024)
{
CurSize // = 1024;
Unit = //'m ///';
If (curSize & gt; 1024)
{
CurSize // = 1024;
Unit = // 'G ///';
}
}
}
Cout <return size;
}
In the du () function, the entryinfolist (qdir: Files) function returns the file information, computes the file size based on the information, and then checks whether there are subdirectories. If yes, recursive calculation is performed. Dir. etnrylist (qdir: dirs | qdir: nodotanddotdot) returns all subdirectories and filters out the... directory. Because of the differences between windows () and Linux platforms, the qdir: separator () function is used to return the directory delimiter of a specific platform. In addition, qdiriterator can complete
The function of enumerating directories. qt4.3 also introduces the file search prefix concept. A file search prefix consists of at least two characters to search for a specified file path.
Qdir: setsearchpaths ("Docs", qstringlist ("C:/My docments "));
Qdir: addsearchpaht ("Docs", qstringlist ("D: | Documents "));
Qfile file ("docs: qt4.doc ");
In this way, you can search in two directories.

File Management
The qfileinfo class provides system-independent file confidence. It provides civilized names and paths, access permissions, and whether the file is a directory or symbolic link, file size, and the last modification/read time. Qfileinfo can also obtain information from resources. Qfileinfo can use relative or absolute paths. The file name can be passed in the constructor of qfileinfo or specified using the setfile () function. To determine whether a function exists, use the exits () function. The file size can be passed through size () function. The file type can be obtained through isfile (), isdir (), and issymlink (). The symlinktarget () function returns the real file name pointed to by the symbolic link. Qfileinfo provides the refresh function to refresh file information. If you need qfileinfo to read information from the file system each time, and do not read information from the cache, you can use setcaching (false) to disable the cache. The file name and directory can be decomposed by path () and filename (). The part returned by filename () can be obtained by basename () and Extension () to obtain the main file name and extended file name, the object operation date can be obtained through created (), lastmodified (), and lastread (). The object access permission can be obtained through isreadable, iswriteable (), isexcutetable, the owner of a file can be obtained through owner (), ownerid, group (), and groupid (). The File Permission and owner can also be read through permission.

Monitor File System Changes
In QT, you can use the qfilesystemwatcher class to monitor file and directory changes. use the addpath () function to monitor specified files and directories. If you need to monitor multiple directories, use addpaths () to add them to the monitoring. If you want a directory that does not need to be monitored, you can use the removepath () and removepaths () functions. when the monitored file is modified or deleted, a filechanged () signal is generated. If the monitored directory is modified or deleted, a directorychanged () signal is generated, the following example shows how to monitor a specified directory.
# Include
# Include
# Include
# Include "Msg. h"
Using namespace std;
Int main (int argc, char ** argv)
{
QApplication app (argc, argv );
QTextCodec: setCodecForTr (QTextCodec: codecForLocale ())

Msg msg;
Msg. show ();
Return app.exe c ();
}
Msg: Msg ()
{
QFont font;
Font. setPointSize (24 );
SetFont (font );
QStringList args = qApp-> arguments ();
QString path;
If (args. count ()> 1)
Path = args [1];
Else
Path = qdir: currentpath ();
Label = new qlabel ();
Label-> settext (TR ("monitored Directory:") + path );

Qvboxlayout * layout = new qvboxlayout;
Layout-> addwidget (Label );
Setlayout (layout );

Fswatcher. addpath (PATH );
Connect (& fswatcher, signal (directorychanged (qstring), this, slot (directorychanged (qstring )));
}
Read the directory specified by the command in the constructor as the monitoring directory. If no directory is specified, monitor the current directory. Use the connect () function to connect the directroychanged () signal of the directory to the response function.
Void MSG: directorychanged (qstring path)
{
Qmessagebox: Information (null, TR ("Directory change"), PATH );
}

File Engine
The QtDir, QFile, and QFileInfo classes of Qt all use a class internally, qw.actfileengine. by inheriting the QAbstractFileEngine class, you can write your own file processing functions, and then inherit the QAbstractFileEngineHander class to register your own file engine. Then you can use your own file reading engine. qw.actfileenginehandler is a class factory for creating qw.actfileengine. when opening a file, Qt selects an appropriate file engine and creates the corresponding engine object through the file engine linked list registered internally. to install a specific file engine, you must inherit QAbstractFileEngineHandler and implement the create () function. qt automatically registers the engine when instantiating the engine. The engine registered at last has a higher priority than the previously registered engine.
If you want to read the tar file engine, you can inherit from the qw.actfileenginehandler class
Class TarEngineHandler: public q1_actfileenginehandler
{
Public:
Qw.actfileengine * create (const QString & fileName) const;
};
The create () function returns the TarEngine object, which is a real file processing class.
Qw.actfileengine * TarEngineHandler: create (const QString & fileName) const
{
Return fileName. toLower (). endsWith (". tar ")? New TarEngine (fileName): 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.