Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

QFile Class Reference

The QFile class is an I/O device that operates on files. More...

#include <QFile>

Inherits QObject and QIODevice.

Inherited by QTemporaryFile.

Note: All the functions in this class are reentrant, except setEncodingFunction() and setDecodingFunction().

Public Types

Writable Properties

Public Functions

Public Slots

Signals

Static Public Members

Protected Functions


Detailed Description

The QFile class is an I/O device that operates on files.

QFile is an I/O device for reading and writing binary and text files. A QFile may be used by itself or, more conveniently, with a QDataStream or QTextStream.

The file name is usually passed in the constructor, but it can be changed with setFileName(). You can check for a file's existence with exists(), and remove a file with remove().

The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can read with read() and readLine(), and write with write(). QFile also supports getch(), ungetch(), and putch().

The size of the file is returned by size(). You can get the current file position or move to a new file position using the at() functions. If you've reached the end of the file, atEnd() returns true. The file handle is returned by handle().

The following example uses QTextStream to read a text file line by line, printing each line with a line number:

    QStringList lines;
    QFile file("file.txt");
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream stream(&file);
        QString line;
        int i = 1;
        while (!stream.atEnd()) {
            line = stream.readLine(); // line of text excluding '\n'
            printf("%3d: %s\n", i++, line.latin1());
            lines += line;
        }
        file.close();
    }

Writing text is just as easy. The following example shows how to write the data we read in the previous example to a file:

    QFile file("file.txt");
    if (file.open(QIODevice::WriteOnly)) {
        QTextStream stream(&file);
        QStringList::ConstIterator i = lines.constBegin();
        for (; i != lines.constEnd(); ++i)
            stream << *i << "\n";
        file.close();
    }

The QFileInfo class holds detailed information about a file, such as access permissions, file dates and file types.

The QDir class manages directories and lists of file names.

When you use QFile, QFileInfo, and QDir to access the file system with Qt, you can use Unicode file names. On Unix, these file names are converted to an 8-bit encoding. If you want to do your own file I/O on Unix, you should convert file names using the encodeName() and decodeName() functions to convert the file name into the local encoding.

The conversion scheme can be changed using setEncodingFunction(). This might be useful if you wish to give the user an option to store file names in UTF-8, for example, but be aware that such file names would probably then be unrecognizable when seen by other programs.

On Windows NT/2000, Unicode file names are supported directly in the file system and this function should be avoided. On Windows 95, non-Latin1 locales are not supported.

See also QDataStream and QTextStream.


Member Type Documentation

typedef QFile::DecoderFn

This is used by QFile::setDecodingFunction() to specify how file names are converted from the local encoding to Unicode.

typedef QFile::EncoderFn

This is used by QFile::setEncodingFunction() to specify how Unicode file names are converted to the appropriate local encoding.

enum QFile::PermissionSpec

This enum is used by the permission() function to report the permissions and ownership of a file. The values may be OR-ed together to test multiple permissions and ownership values.

QFile::ReadOwnerThe file is readable by the owner of the file.
QFile::WriteOwnerThe file is writable by the owner of the file.
QFile::ExeOwnerThe file is executable by the owner of the file.
QFile::ReadUserThe file is readable by the user.
QFile::WriteUserThe file is writable by the user.
QFile::ExeUserThe file is executable by the user.
QFile::ReadGroupThe file is readable by the group.
QFile::WriteGroupThe file is writable by the group.
QFile::ExeGroupThe file is executable by the group.
QFile::ReadOtherThe file is readable by anyone.
QFile::WriteOtherThe file is writable by anyone.
QFile::ExeOtherThe file is executable by anyone.

Warning: The semantics of ReadUser, WriteUser and ExeUser are unfortunately not platform independent: on Unix, the rights of the owner of the file are returned and on Windows the rights of the current user are returned. This behavior might change in a future Qt version. If you want to find the rights of the owner of the file, you should use the flags ReadOwner, WriteOwner and ExeOwner. If you want to find out the rights of the current user, you should use isReadable(), isWritable() and isExecutable().


Member Function Documentation

QFile::QFile ()

Constructs a QFile with no name.

QFile::QFile ( QObject * parent )

Constructs a QFile with no name.

The parent is passed to the QObject constructor.

QFile::QFile ( const QString & name )

Constructs a QFile with a file name name.

See also setFileName().

QFile::~QFile ()

Destroys the file object, closing it if necessary.

bool QFile::copy ( const QString & newName )

Copies the file currently specified by fileName() to newName. Returns true if successful; otherwise returns false.

The file is closed before it is copied.

See also setFileName().

bool QFile::copy ( const QString & fileName, const QString & newName )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Copies the file fileName to newName. Returns true if successful; otherwise returns false.

See also rename().

QString QFile::decodeName ( const QByteArray & localFileName )   [static]

This does the reverse of QFile::encodeName() using localFileName.

See also setDecodingFunction().

QString QFile::decodeName ( const char * localFileName )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the Unicode version of the given localFileName. See encodeName() for details.

QByteArray QFile::encodeName ( const QString & fileName )   [static]

By default, this function converts fileName to the local 8-bit encoding determined by the user's locale. This is sufficient for file names that the user chooses. File names hard-coded into the application should only use 7-bit ASCII filename characters.

See also decodeName() and setEncodingFunction().

bool QFile::exists ( const QString & fileName )   [static]

Returns true if the file specified by fileName exists; otherwise returns false.

bool QFile::exists () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns true if the file specified by fileName() exists; otherwise returns false.

See also fileName() and setFileName().

QFileEngine * QFile::fileEngine () const   [virtual]

Returns the QIOEngine for this QFile object.

QString QFile::fileName () const

Returns the name set by setFileName().

See also setFileName() and QFileInfo::fileName().

int QFile::handle () const

Returns the file handle of the file.

This is a small positive integer, suitable for use with C library functions such as fdopen() and fcntl(). On systems that use file descriptors for sockets (i.e. Unix systems, but not Windows) the handle can be used with QSocketNotifier as well.

If the file is not open, or there is an error, handle() returns -1.

See also QSocketNotifier.

bool QFile::link ( const QString & newName )

Creates a link from the file currently specified by fileName() to newName. What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful; otherwise returns false.

See also setFileName().

bool QFile::link ( const QString & oldName, const QString & newName )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Creates a link from oldName to newName. What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true if successful; otherwise returns false.

See also link().

bool QFile::open ( int mode, FILE * fh )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Opens the existing file handle fh in the given mode. Returns true if successful; otherwise returns false.

Example:

    #include <stdio.h>

    void printError(const char* msg)
    {
        QFile file;
        file.open(QIODevice::WriteOnly, stderr);
        file.write(msg, qstrlen(msg));        // write to stderr
        file.close();
    }

When a QFile is opened using this function, close() does not actually close the file, but only flushes it.

Warning: If fh is stdin, stdout, or stderr, you may not be able to seek(). See QIODevice::isSequentialAccess() for more information.

See also close().

bool QFile::open ( int mode, int fd )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Opens the existing file descripter fd in the given mode. Returns true if successful; otherwise returns false.

When a QFile is opened using this function, close() does not actually close the file.

The QFile that is opened using this function is automatically set to be in raw mode; this means that the file input/output functions are slow. If you run into performance issues, you should try to use one of the other open functions.

Warning: If fd is 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). size() is set to LLONG_MAX (in limits.h).

See also close().

uint QFile::permissions () const

Returns the complete OR-ed together combination of QFile::PermissionSpec for the file.

See also QFile::setPermissions, QFile::PermissionSpec, and setFileName().

uint QFile::permissions ( const QString & fileName )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the complete OR-ed together combination of QFile::PermissionSpec for fileName.

See also permissions() and QFile::PermissionSpec.

Q_LONGLONG QFile::readLine ( QString & str, Q_LONGLONG maxSize )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Reads a line of text.

Reads bytes from the file into the str until end-of-line or maxSize bytes have been read, whichever occurs first. Returns the number of bytes read, or -1 if there was an error (e.g. end of file). Any terminating newline is not stripped.

This function is only efficient for buffered files. Avoid using readLine() for files that have been opened with the QIODevice::Raw flag.

Note that the string is read as plain Latin-1 bytes, not Unicode.

See also read() and QTextStream::readLine().

bool QFile::remove ()

Removes the file specified by fileName(). Returns true if successful; otherwise returns false.

The file is closed before it is removed.

See also setFileName().

bool QFile::remove ( const QString & fileName )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Removes the file specified by the fileName given.

Returns true if successful; otherwise returns false.

See also remove().

bool QFile::rename ( const QString & newName )

Renames the file currently specified by fileName() to newName. Returns true if successful; otherwise returns false.

The file is closed before it is renamed.

See also setFileName().

bool QFile::rename ( const QString & oldName, const QString & newName )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Renames the file oldName to newName. Returns true if successful; otherwise returns false.

See also rename().

bool QFile::resize ( QIODevice::Offset sz )

Sets the file size (in bytes) sz. Returns true if the file if the resize succeeds; false otherwise. If sz is larger than the file currently is the new bytes will be set to 0, if sz is smaller the file is simply truncated.

See also QFile::size() and setFileName().

bool QFile::resize ( const QString & fileName, QIODevice::Offset sz )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Sets fileName to size (in bytes) sz. Returns true if the file if the resize succeeds; false otherwise. If sz is larger than fileName currently is the new bytes will be set to 0, if sz is smaller the file is simply truncated.

See also resize().

void QFile::setDecodingFunction ( DecoderFn function )   [static]

Sets the function for decoding 8-bit file names. The default uses the locale-specific 8-bit encoding.

Warning: This function is not reentrant.

See also encodeName() and decodeName().

void QFile::setEncodingFunction ( EncoderFn function )   [static]

Sets the function for encoding Unicode file names. The default encodes in the locale-specific 8-bit encoding.

Warning: This function is not reentrant.

See also encodeName().

void QFile::setFileName ( const QString & name )

Sets the name of the file. The name can have no path, a relative path, or an absolute absolute path.

Do not call this function if the file has already been opened.

If the file name has no path or a relative path, the path used will be the application's current directory path at the time of the open() call.

Example:

    QFile file;
    QDir::setCurrent("/tmp");
    file.setFileName("readme.txt");
    QDir::setCurrent("/home");
    file.open(QIODevice::ReadOnly);      // opens "/home/readme.txt" under Unix

Note that the directory separator "/" works for all operating systems supported by Qt.

See also fileName(), QFileInfo, and QDir.

bool QFile::setPermissions ( uint permissionSpec )

Sets the permissions for the file to permissionSpec. The permissionSpec argument can be several flags of type QFile::PermissionSpec OR-ed together to set the file to.

See also permissions(), QFile::PermissionSpec, and setFileName().

bool QFile::setPermissions ( const QString & fileName, uint permissionSpec )   [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Sets the permissions for fileName file to permissionSpec. The permissionSpec argument can be several flags of type QFile::PermissionSpec OR-ed together to set the file to.

See also setPermissions().


Copyright © 2004 Trolltech. Trademarks
Qt 4.0.0-tp2