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 QIODevice.

Inherited by QTemporaryFile.

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

- List of all members, including inherited members
- Compatibility members

### Public Types

- typedef DecoderFn
- typedef EncoderFn
- enum Error { NoError, ReadError, WriteError, FatalError, ResourceError, ..., ConnectError }
- enum Permission { ReadOwner, WriteOwner, ExeOwner, ReadUser, WriteUser, ..., ExeOther }
- typedef PermissionSpec
- typedef Permissions

### Writable Properties

- 1 writable property inherited from QObject

### Public Functions

- QFile ()
- QFile ( const QString & name )
- QFile ( QObject * parent )
- QFile ( const QString & name, QObject * parent )
- ~QFile ()
- bool copy ( const QString & newName )
- Error error () const
- bool exists () const
- virtual QFileEngine * fileEngine () const
- QString fileName () const
- int handle () const
- bool isOpen () const
- virtual bool isSequential () const
- bool link ( const QString & newName )
- bool open ( OpenMode flags, FILE * fh )
- bool open ( OpenMode flags, int fd )
- Permissions permissions () const
- QString readLink () const
- bool remove ()
- bool rename ( const QString & newName )
- bool resize ( Q_LONGLONG sz )
- void setFileName ( const QString & name )
- bool setPermissions ( Permissions permissionSpec )
- void unsetError ()

- 29 public functions inherited from QIODevice
- 26 public functions inherited from QObject

### Public Slots

- 1 public slot inherited from QObject

### Signals

- 2 signals inherited from QIODevice
- 1 signal inherited from QObject

### Static Public Members

- bool copy ( const QString & fileName, const QString & newName )
- QString decodeName ( const QByteArray & localFileName )
- QString decodeName ( const char * localFileName )
- QByteArray encodeName ( const QString & fileName )
- bool exists ( const QString & fileName )
- bool link ( const QString & oldName, const QString & newName )
- Permissions permissions ( const QString & fileName )
- QString readLink ( const QString & fileName )
- bool remove ( const QString & fileName )
- bool rename ( const QString & oldName, const QString & newName )
- bool resize ( const QString & fileName, Q_LONGLONG sz )
- void setDecodingFunction ( DecoderFn function )
- void setEncodingFunction ( EncoderFn function )
- bool setPermissions ( const QString & filename, Permissions permissionSpec )

- 4 static public members inherited from QObject

### Protected Functions

- QFile ( QFilePrivate & d, QObject * parent )

- 4 protected functions inherited from QIODevice
- 7 protected functions inherited from QObject

## 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 and resources. 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, QTextStream, and Qt's Resource System.

## 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::Error

### enum QFile::Permission
typedef QFile::Permissions

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::ReadOwner` | The file is readable by the owner of the file.
`QFile::WriteOwner` | The file is writable by the owner of the file.
`QFile::ExeOwner` | The file is executable by the owner of the file.
`QFile::ReadUser` | The file is readable by the user.
`QFile::WriteUser` | The file is writable by the user.
`QFile::ExeUser` | The file is executable by the user.
`QFile::ReadGroup` | The file is readable by the group.
`QFile::WriteGroup` | The file is writable by the group.
`QFile::ExeGroup` | The file is executable by the group.
`QFile::ReadOther` | The file is readable by anyone.
`QFile::WriteOther` | The file is writable by anyone.
`QFile::ExeOther` | The 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().

The Permissions typedef can store a combination of Permission values.

### typedef QFile::PermissionSpec

## Member Function Documentation

### QFile::QFile ()

### QFile::QFile ( const QString & name )

### QFile::QFile ( QObject * parent )

### QFile::QFile ( const QString & name, QObject * parent )

### QFile::QFile ( QFilePrivate & d, QObject * parent ) `[protected]`

### 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().

### Error QFile::error () const

Returns the file error status.

The I/O device status returns an error code. For example, if open() returns false, or a read/write operation returns -1, this function can be called to find out the reason why the operation failed.

The status codes are:

Status code | Meaning
--- | ---
`QFile::NoError` | The operation was successful.
`QFile::ReadError` | Could not read from the device.
`QFile::WriteError` | Could not write to the device.
`QFile::FatalError` | A fatal unrecoverable error occurred.
`QFile::OpenError` | Could not open the device.
`QFile::ConnectError` | Could not connect to the device.
`QFile::AbortError` | The operation was unexpectedly aborted.
`QFile::TimeOutError` | The operation timed out.
`QFile::UnspecifiedError` | An unspecified error happened on close.

See also unsetError().

### 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::isOpen () const

Returns true if the file is open; otherwise returns false.

See also open() and close().

### bool QFile::isSequential () const `[virtual]`

### 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 ( OpenMode flags, 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 ( OpenMode flags, 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().

### Permissions QFile::permissions () const

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

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

### Permissions 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::Permission for fileName.

See also permissions() and QFile::Permission.

### QString QFile::readLink ( const QString & fileName ) `[static]`

Returns the name a symlink (or shortcut on Windows) points to, or a an empty string if the object isn't a symbolic link.

This name may not represent an existing file; it is only a string. QFie::exists() returns true if the symlink points to an existing file.

### QString QFile::readLink () const

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

Returns the name a symlink (or shortcut on Windows) points to, or a an empty string if the object isn't a symbolic link.

This name may not represent an existing file; it is only a string. QFie::exists() returns true if the symlink points to an existing file.

See also fileName() and setFileName().

### 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 ( Q_LONGLONG 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, Q_LONGLONG 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 ( Permissions permissionSpec )

### bool QFile::setPermissions ( const QString & filename, Permissions permissionSpec ) `[static]`

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

### void QFile::unsetError ()

Sets the file's error to `QFile::NoError`.

See also error().