QFile Class Reference
[QtCore module]
The QFile class provides an interface for reading from and
writing to files. More…
Inherits QIODevice.
Inherited by QTemporaryFile.
Types
-
enum FileError { NoError, ReadError, WriteError, FatalError, …, CopyError }
-
enum Permission { ReadOwner, WriteOwner, ExeOwner, ReadUser, …, ExeOther }
Methods
-
__init__ (self, QString name, QObject parent)
-
bool copy (self, QString newName)
-
FileError error (self)
-
bool link (self, QString newName)
-
sip.voidptr map (self, int offset, int size, MemoryMapFlags flags = QFile.NoOptions)
-
bool open (self, QIODevice.OpenMode flags)
-
bool open (self, int fd, QIODevice.OpenMode flags)
-
bool open (self, int fd, QIODevice.OpenMode flags, FileHandleFlags handleFlags)
-
int pos (self)
-
bool rename (self, QString newName)
-
bool resize (self, int sz)
-
bool seek (self, int offset)
-
bool unmap (self, sip.voidptr address)
Static Methods
-
bool copy (QString fileName, QString newName)
-
QString decodeName (QByteArray localFileName)
-
bool exists (QString fileName)
-
bool link (QString oldname, QString newName)
-
QString readLink (QString fileName)
-
bool remove (QString fileName)
-
bool rename (QString oldName, QString newName)
-
bool resize (QString filename, int sz)
-
bool setPermissions (QString filename, Permissions permissionSpec)
Detailed Description
The QFile class provides an interface for reading from and
writing to files.
QFile is an I/O device for reading and writing text and binary
files and resources. A QFile may be
used by itself or, more conveniently, with a QTextStream or QDataStream.
The file name is usually passed in the constructor, but it can
be set at any time using setFileName(). QFile expects the file
separator to be ‘/’ regardless of operating system. The use of
other separators (e.g., ») is not supported.
You can check for a file’s existence using exists(), and remove a file using remove(). (More advanced file system
related operations are provided by QFileInfo and QDir.)
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 also call
the QIODevice-inherited functions
read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one
character at a time.
The size of the file is returned by size(). You can get the current file position
using pos(), or move to a new file
position using seek(). If you’ve
reached the end of the file, atEnd()
returns true.
Reading Files Directly
The following example reads a text file line by line:
QFile file("in.txt"); if (!file.open(QIODevice.ReadOnly | QIODevice.Text)) return; while (!file.atEnd()) { QByteArray line = file.readLine(); process_line(line); }
The QIODevice.Text flag passed
to open() tells Qt to convert
Windows-style line terminators («rn») into C++-style terminators
(«n»). By default, QFile assumes binary, i.e. it doesn’t perform
any conversion on the bytes stored in the file.
Using Streams to Read Files
The next example uses QTextStream
to read a text file line by line:
QFile file("in.txt"); if (!file.open(QIODevice.ReadOnly | QIODevice.Text)) return; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); process_line(line); }
QTextStream takes care of
converting the 8-bit data stored on disk into a 16-bit Unicode
QString. By default, it assumes that the
user system’s local 8-bit encoding is used (e.g., ISO 8859-1 for
most of Europe; see QTextCodec.codecForLocale()
for details). This can be changed using setCodec().
To write text, we can use operator<<(), which is
overloaded to take a QTextStream on
the left and various data types (including QString) on the right:
QFile file("out.txt"); if (!file.open(QIODevice.WriteOnly | QIODevice.Text)) return; QTextStream out(&file); out << "The magic number is: " << 49 << "n";
QDataStream is similar, in that
you can use operator<<() to write data and operator>>()
to read it back. See the class documentation for details.
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 use standard C++ APIs
(<cstdio> or <iostream>) or
platform-specific APIs to access files instead of QFile, you can
use the encodeName() and
decodeName() functions to
convert between Unicode file names and 8-bit file names.
On Unix, there are some special system files (e.g. in
/proc) for which size() will
always return 0, yet you may still be able to read more data from
such a file; the data is generated in direct response to you
calling read(). In this case,
however, you cannot use atEnd() to
determine if there is more data to read (since atEnd() will return true for a file that
claims to have size 0). Instead, you should either call readAll(), or call read() or readLine() repeatedly until no more
data can be read. The next example uses QTextStream to read /proc/modules
line by line:
QFile file("/proc/modules"); if (!file.open(QIODevice.ReadOnly | QIODevice.Text)) return; QTextStream in(&file); QString line = in.readLine(); while (!line.isNull()) { process_line(line); line = in.readLine(); }
Signals
Unlike other QIODevice
implementations, such as QTcpSocket,
QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This
implementation detail means that QFile is not suitable for reading
and writing certain types of files, such as device files on Unix
platforms.
Platform Specific Issues
File permissions are handled differently on Linux/Mac OS X and
Windows. In a non writable
directory on Linux, files cannot be created. This is not always the
case on Windows, where, for instance, the ‘My Documents’ directory
usually is not writable, but it is still possible to create files
in it.
Type Documentation
QFile.FileError
This enum describes the errors that may be returned by the
error() function.
Constant | Value | Description |
---|---|---|
QFile.NoError | 0 | No error occurred. |
QFile.ReadError | 1 | An error occurred when reading from the file. |
QFile.WriteError | 2 | An error occurred when writing to the file. |
QFile.FatalError | 3 | A fatal error occurred. |
QFile.ResourceError | 4 | |
QFile.OpenError | 5 | The file could not be opened. |
QFile.AbortError | 6 | The operation was aborted. |
QFile.TimeOutError | 7 | A timeout occurred. |
QFile.UnspecifiedError | 8 | An unspecified error occurred. |
QFile.RemoveError | 9 | The file could not be removed. |
QFile.RenameError | 10 | The file could not be renamed. |
QFile.PositionError | 11 | The position in the file could not be changed. |
QFile.ResizeError | 12 | The file could not be resized. |
QFile.PermissionsError | 13 | The file could not be accessed. |
QFile.CopyError | 14 | The file could not be copied. |
QFile.FileHandleFlag
This enum is used when opening a file to specify additional
options which only apply to files and not to a generic QIODevice.
Constant | Value | Description |
---|---|---|
QFile.AutoCloseHandle | 0x0001 | The file handle passed into open() should be closed by close(), the default behaviour is that close just flushes the file and the application is responsible for closing the file handle. When opening a file by name, this flag is ignored as Qt always «owns» the file handle and must close it. |
QFile.DontCloseHandle | 0 | The file handle passed into open() will not be closed by Qt. The application must ensure that close() is called. |
This enum was introduced or modified in Qt 4.8.
The FileHandleFlags type is a typedef for QFlags<FileHandleFlag>. It stores an OR
combination of FileHandleFlag values.
QFile.MemoryMapFlags
This enum describes special options that may be used by the
map() function.
Constant | Value | Description |
---|---|---|
QFile.NoOptions | 0 | No options. |
This enum was introduced or modified in Qt 4.4.
QFile.Permission
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.
Constant | Value | Description |
---|---|---|
QFile.ReadOwner | 0x4000 | The file is readable by the owner of the file. |
QFile.WriteOwner | 0x2000 | The file is writable by the owner of the file. |
QFile.ExeOwner | 0x1000 | The file is executable by the owner of the file. |
QFile.ReadUser | 0x0400 | The file is readable by the user. |
QFile.WriteUser | 0x0200 | The file is writable by the user. |
QFile.ExeUser | 0x0100 | The file is executable by the user. |
QFile.ReadGroup | 0x0040 | The file is readable by the group. |
QFile.WriteGroup | 0x0020 | The file is writable by the group. |
QFile.ExeGroup | 0x0010 | The file is executable by the group. |
QFile.ReadOther | 0x0004 | The file is readable by anyone. |
QFile.WriteOther | 0x0002 | The file is writable by anyone. |
QFile.ExeOther | 0x0001 | The file is executable by anyone. |
Warning: Because of differences in the platforms
supported by Qt, the semantics of ReadUser, WriteUser and ExeUser
are platform-dependent: 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.
Note that Qt does not by default check for permissions on NTFS
file systems, as this may decrease the performance of file handling
considerably. It is possible to force permission checking on NTFS
by including the following code in your source:
extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
Permission checking is then turned on and off by incrementing
and decrementing qt_ntfs_permission_lookup by 1.
qt_ntfs_permission_lookup++; qt_ntfs_permission_lookup--;
The Permissions type is a typedef for QFlags<Permission>. It stores an OR
combination of Permission values.
Method Documentation
QFile.__init__ (self)
Constructs a new file object to represent the file with the
given name.
QFile.__init__ (self, QString name)
QFile.__init__ (self, QObject parent)
The parent argument, if not None, causes self to be owned by Qt instead of PyQt.
Constructs a new file object with the given parent.
QFile.__init__ (self, QString name, QObject parent)
The parent argument, if not None, causes self to be owned by Qt instead of PyQt.
Constructs a new file object with the given parent to
represent the file with the specified name.
bool QFile.atEnd (self)
Reimplemented from QIODevice.atEnd().
Returns true if the end of the file has been reached; otherwise
returns false.
For regular empty files on Unix (e.g. those in /proc),
this function returns true, since the file system reports that the
size of such a file is 0. Therefore, you should not depend on
atEnd() when reading data from such a file, but rather call
read() until no more data can be
read.
QFile.close (self)
Reimplemented from QIODevice.close().
Calls QFile.flush() and closes
the file. Errors from flush are ignored.
See also QIODevice.close().
bool QFile.copy (self, QString newName)
Copies the file currently specified by fileName() to a file called
newName. Returns true if successful; otherwise returns
false.
Note that if a file with the name newName already exists,
copy() returns false (i.e. QFile will not
overwrite it).
The source file is closed before it is copied.
See also setFileName().
bool QFile.copy (QString fileName, QString newName)
This is an overloaded function.
Copies the file fileName to newName. Returns true
if successful; otherwise returns false.
If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).
See also rename().
QString QFile.decodeName (QByteArray localFileName)
This does the reverse of QFile.encodeName() using
localFileName.
See also setDecodingFunction() and
encodeName().
QString QFile.decodeName (str localFileName)
This is an overloaded function.
Returns the Unicode version of the given localFileName.
See encodeName() for
details.
QByteArray QFile.encodeName (QString fileName)
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().
FileError QFile.error (self)
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.
See also unsetError().
bool QFile.exists (self)
Returns true if the file specified by fileName exists;
otherwise returns false.
bool QFile.exists (QString fileName)
This is an overloaded function.
Returns true if the file specified by fileName() exists; otherwise returns
false.
See also fileName() and
setFileName().
QAbstractFileEngine QFile.fileEngine (self)
QString QFile.fileName (self)
Returns the name set by setFileName() or to the QFile constructors.
See also setFileName() and QFileInfo.fileName().
bool QFile.flush (self)
Flushes any buffered data to the file. Returns true if
successful; otherwise returns false.
int QFile.handle (self)
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.
This function is not supported on Windows CE.
On Symbian, this function returns -1 if the file was opened
normally, as Symbian OS native file handles do not fit in an int,
and are incompatible with C library functions that the handle would
be used for. If the file was opened using the overloads that take
an open C library file handle / file descriptor, then this function
returns that same handle.
See also QSocketNotifier.
bool QFile.isSequential (self)
Reimplemented from QIODevice.isSequential().
Returns true if the file can only be manipulated sequentially;
otherwise returns false.
Most files support random-access, but some special files may
not.
See also QIODevice.isSequential().
bool QFile.link (self, QString newName)
Creates a link named linkName that points to the file
currently specified by fileName(). 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.
This function will not overwrite an already existing entity in
the file system; in this case, link() will return false
and set error() to return RenameError.
Note: To create a valid link on Windows, linkName
must have a .lnk file extension.
Note: Symbian filesystem does not support links.
See also setFileName().
bool QFile.link (QString oldname, QString newName)
This is an overloaded function.
Creates a link named linkName that points to the file
fileName. 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().
sip.voidptr QFile.map (self, int offset, int size, MemoryMapFlags flags = QFile.NoOptions)
Maps size bytes of the file into memory starting at
offset. A file should be open for a map to succeed but the
file does not need to stay open after the memory has been mapped.
When the QFile is destroyed or a new file
is opened with this object, any maps that have not been unmapped
will automatically be unmapped.
Any mapping options can be passed through flags.
Returns a pointer to the memory or 0 if there is an error.
Note: On Windows CE 5.0 the file will be closed before
mapping occurs.
This function was introduced in Qt 4.4.
See also unmap() and
QAbstractFileEngine.supportsExtension().
bool QFile.open (self, QIODevice.OpenMode flags)
Reimplemented from QIODevice.open().
Opens the file using OpenMode mode,
returning true if successful; otherwise false.
The mode must be QIODevice.ReadOnly,
QIODevice.WriteOnly,
or QIODevice.ReadWrite. It may
also have additional flags, such as QIODevice.Text and QIODevice.Unbuffered.
Note: In WriteOnly or ReadWrite mode, if the
relevant file does not already exist, this function will try to
create a new file before opening it.
See also QIODevice.OpenMode and
setFileName().
bool QFile.open (self, int fd, QIODevice.OpenMode flags)
bool QFile.open (self, int fd, QIODevice.OpenMode flags, FileHandleFlags handleFlags)
Permissions QFile.permissions (self)
Returns the complete OR-ed together combination of QFile.Permission for the
file.
See also setPermissions() and setFileName().
Permissions QFile.permissions (QString filename)
This is an overloaded function.
Returns the complete OR-ed together combination of QFile.Permission for
fileName.
int QFile.pos (self)
Reimplemented from QIODevice.pos().
str QFile.readData (self, int maxlen)
Reimplemented from QIODevice.readData().
str QFile.readLineData (self, int maxlen)
Reimplemented from QIODevice.readLineData().
QString QFile.readLink (self)
QString QFile.readLink (QString fileName)
bool QFile.remove (self)
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 (QString fileName)
This is an overloaded function.
Removes the file specified by the fileName given.
Returns true if successful; otherwise returns false.
See also remove().
bool QFile.rename (self, QString newName)
Renames the file currently specified by fileName() to newName. Returns
true if successful; otherwise returns false.
If a file with the name newName already exists, rename()
returns false (i.e., QFile will not
overwrite it).
The file is closed before it is renamed.
See also setFileName().
bool QFile.rename (QString oldName, QString newName)
This is an overloaded function.
Renames the file oldName to newName. Returns true
if successful; otherwise returns false.
If a file with the name newName already exists, rename() returns false (i.e., QFile will not overwrite it).
See also rename().
bool QFile.resize (self, int 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 size() and
setFileName().
bool QFile.resize (QString filename, int sz)
This is an overloaded 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().
bool QFile.seek (self, int offset)
Reimplemented from QIODevice.seek().
For random-access devices, this function sets the current
position to pos, returning true on success, or false if an
error occurred. For sequential devices, the default behavior is to
do nothing and return false.
Seeking beyond the end of a file: If the position is beyond the
end of a file, then seek() shall not immediately extend the file.
If a write is performed at this position, then the file shall be
extended. The content of the file between the previous end of file
and the newly written data is UNDEFINED and varies between
platforms and file systems.
QFile.setFileName (self, QString name)
Sets the name of the file. The name can have no path, a
relative path, or an 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);
Note that the directory separator «/» works for all operating
systems supported by Qt.
See also fileName(),
QFileInfo, and QDir.
bool QFile.setPermissions (self, Permissions permissionSpec)
Sets the permissions for the file to the permissions
specified. Returns true if successful, or false if the permissions
cannot be modified.
See also permissions() and setFileName().
bool QFile.setPermissions (QString filename, Permissions permissionSpec)
This is an overloaded function.
Sets the permissions for fileName file to
permissions.
int QFile.size (self)
Reimplemented from QIODevice.size().
Returns the size of the file.
For regular empty files on Unix (e.g. those in /proc),
this function returns 0; the contents of such a file are generated
on demand in response to you calling read().
QString QFile.symLinkTarget (self)
Returns the absolute path of the file or directory referred to
by the symlink (or shortcut on Windows) specified by
fileName, or returns an empty string if the fileName
does not correspond to a symbolic link.
This name may not represent an existing file; it is only a
string. QFile.exists() returns
true if the symlink points to an existing file.
This function was introduced in Qt 4.2.
QString QFile.symLinkTarget (QString fileName)
This is an overloaded function.
Returns the absolute path of the file or directory 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. QFile.exists() returns
true if the symlink points to an existing file.
This function was introduced in Qt 4.2.
See also fileName() and
setFileName().
bool QFile.unmap (self, sip.voidptr address)
Unmaps the memory address.
Returns true if the unmap succeeds; false otherwise.
This function was introduced in Qt 4.4.
See also map() and QAbstractFileEngine.supportsExtension().
QFile.unsetError (self)
Sets the file’s error to QFile.NoError.
See also error().
int QFile.writeData (self, str data)
Reimplemented from QIODevice.writeData().
The QFile class provides an interface for reading from and writing to files.
More…
#include <qfile.h>
Public Types |
|
typedef QString(* | DecoderFn) (const QByteArray &localfileName) |
This is a typedef for a pointer to a function with the following signature: More… | |
typedef QByteArray(* | EncoderFn) (const QString &fileName) |
This is a typedef for a pointer to a function with the following signature: More… | |
enum | FileError { NoError = 0, ReadError = 1, WriteError = 2, FatalError = 3, ResourceError = 4, OpenError = 5, AbortError = 6, TimeOutError = 7, UnspecifiedError = 8, RemoveError = 9, RenameError = 10, PositionError = 11, ResizeError = 12, PermissionsError = 13, CopyError = 14 } |
This enum describes the errors that may be returned by the error() function. More… | |
enum | FileHandleFlag { AutoCloseHandle = 0x0001, DontCloseHandle = 0 } |
This enum is used when opening a file to specify additional options which only apply to files and not to a generic QIODevice. More… | |
enum | MemoryMapFlags { NoOptions = 0 } |
This enum describes special options that may be used by the map() function. More… | |
enum | Permission { ReadOwner = 0x4000, WriteOwner = 0x2000, ExeOwner = 0x1000, ReadUser = 0x0400, WriteUser = 0x0200, ExeUser = 0x0100, ReadGroup = 0x0040, WriteGroup = 0x0020, ExeGroup = 0x0010, ReadOther = 0x0004, WriteOther = 0x0002, ExeOther = 0x0001 } |
This enum is used by the permission() function to report the permissions and ownership of a file. More… | |
Public Types inherited from QIODevice | |
enum | OpenModeFlag { NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly, Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020 } |
This enum is used with open() to describe the mode in which a device is opened. More… | |
Public Functions |
|
bool | atEnd () const |
Returns true if the end of the file has been reached; otherwise returns false. More… | |
virtual void | close () |
Calls QFile::flush() and closes the file. More… | |
bool | copy (const QString &newName) |
Copies the file currently specified by fileName() to a file called newName. More… | |
FileError | error () const |
Returns the file error status. More… | |
bool | exists () const |
Returns true if the file specified by fileName() exists; otherwise returns false. More… | |
virtual QAbstractFileEngine * | fileEngine () const |
Returns the QIOEngine for this QFile object. More… | |
QString | fileName () const |
Returns the name set by setFileName() or to the QFile constructors. More… | |
bool | flush () |
Flushes any buffered data to the file. More… | |
int | handle () const |
Returns the file handle of the file. More… | |
bool | isSequential () const |
Returns true if the file can only be manipulated sequentially; otherwise returns false. More… | |
bool | link (const QString &newName) |
Creates a link named linkName that points to the file currently specified by fileName(). More… | |
uchar * | map (qint64 offset, qint64 size, MemoryMapFlags flags=NoOptions) |
Maps size bytes of the file into memory starting at offset. More… | |
bool | open (OpenMode flags) |
Opens the file using OpenMode mode, returning true if successful; otherwise false. More… | |
bool | open (FILE *f, OpenMode flags) |
Opens the existing file handle fh in the given mode. More… | |
bool | open (int fd, OpenMode flags) |
Opens the existing file descriptor fd in the given mode. More… | |
bool | open (FILE *f, OpenMode ioFlags, FileHandleFlags handleFlags) |
Opens the existing file handle fh in the given mode. More… | |
bool | open (int fd, OpenMode ioFlags, FileHandleFlags handleFlags) |
Opens the existing file descriptor fd in the given mode. More… | |
Permissions | permissions () const |
Returns the complete OR-ed together combination of QFile::Permission for the file. More… | |
qint64 | pos () const |
Reimplemented Function More… | |
QFile () | |
QFile (const QString &name) | |
Constructs a new file object to represent the file with the given name. More… | |
QFile (QObject *parent) | |
Constructs a new file object with the given parent. More… | |
QFile (const QString &name, QObject *parent) | |
Constructs a new file object with the given parent to represent the file with the specified name. More… | |
QString | readLink () const |
Use symLinkTarget() instead. More… | |
bool | remove () |
Removes the file specified by fileName(). More… | |
bool | rename (const QString &newName) |
Renames the file currently specified by fileName() to newName. More… | |
bool | resize (qint64 sz) |
Sets the file size (in bytes) sz. More… | |
bool | seek (qint64 offset) |
For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More… | |
void | setFileName (const QString &name) |
Sets the name of the file. More… | |
bool | setPermissions (Permissions permissionSpec) |
Sets the permissions for the file to the permissions specified. More… | |
qint64 | size () const |
Returns the size of the file. More… | |
QString | symLinkTarget () const |
Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn’t a symbolic link. More… | |
bool | unmap (uchar *address) |
Unmaps the memory address. More… | |
void | unsetError () |
Sets the file’s error to QFile::NoError. More… | |
~QFile () | |
Destroys the file object, closing it if necessary. More… | |
Public Functions inherited from QIODevice | |
virtual qint64 | bytesAvailable () const |
Returns the number of bytes that are available for reading. More… | |
virtual qint64 | bytesToWrite () const |
For buffered devices, this function returns the number of bytes waiting to be written. More… | |
virtual bool | canReadLine () const |
Returns true if a complete line of data can be read from the device; otherwise returns false. More… | |
QString | errorString () const |
Returns a human-readable description of the last device error that occurred. More… | |
bool | getChar (char *c) |
Reads one character from the device and stores it in c. More… | |
bool | isOpen () const |
Returns true if the device is open; otherwise returns false. More… | |
bool | isReadable () const |
Returns true if data can be read from the device; otherwise returns false. More… | |
bool | isTextModeEnabled () const |
Returns true if the Text flag is enabled; otherwise returns false. More… | |
bool | isWritable () const |
Returns true if data can be written to the device; otherwise returns false. More… | |
OpenMode | openMode () const |
Returns the mode in which the device has been opened; i.e. More… | |
qint64 | peek (char *data, qint64 maxlen) |
Reads at most maxSize bytes from the device into data, without side effects (i. More… | |
QByteArray | peek (qint64 maxlen) |
Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More… | |
bool | putChar (char c) |
Writes the character c to the device. More… | |
QIODevice () | |
Constructs a QIODevice object. More… | |
QIODevice (QObject *parent) | |
Constructs a QIODevice object with the given parent. More… | |
qint64 | read (char *data, qint64 maxlen) |
Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More… | |
QByteArray | read (qint64 maxlen) |
Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More… | |
QByteArray | readAll () |
Reads all available data from the device, and returns it as a QByteArray. More… | |
qint64 | readLine (char *data, qint64 maxlen) |
This function reads a line of ASCII characters from the device, up to a maximum of maxSize — 1 bytes, stores the characters in data, and returns the number of bytes read. More… | |
QByteArray | readLine (qint64 maxlen=0) |
Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More… | |
virtual bool | reset () |
Seeks to the start of input for random-access devices. More… | |
void | setTextModeEnabled (bool enabled) |
If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More… | |
void | ungetChar (char c) |
Puts the character c back into the device, and decrements the current position unless the position is 0. More… | |
virtual bool | waitForBytesWritten (int msecs) |
For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. More… | |
virtual bool | waitForReadyRead (int msecs) |
Blocks until new data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. More… | |
qint64 | write (const char *data, qint64 len) |
Writes at most maxSize bytes of data from data to the device. More… | |
qint64 | write (const char *data) |
Writes data from a zero-terminated string of 8-bit characters to the device. More… | |
qint64 | write (const QByteArray &data) |
Writes the content of byteArray to the device. More… | |
virtual | ~QIODevice () |
The destructor is virtual, and QIODevice is an abstract base class. More… | |
Public Functions inherited from QObject | |
bool | blockSignals (bool b) |
If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More… | |
const QObjectList & | children () const |
Returns a list of child objects. More… | |
bool | connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const |
bool | disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0) |
bool | disconnect (const QObject *receiver, const char *member=0) |
void | dumpObjectInfo () |
Dumps information about signal connections, etc. More… | |
void | dumpObjectTree () |
Dumps a tree of children to the debug output. More… | |
QList< QByteArray > | dynamicPropertyNames () const |
Returns the names of all properties that were dynamically added to the object using setProperty(). More… | |
virtual bool | event (QEvent *) |
This virtual function receives events to an object and should return true if the event e was recognized and processed. More… | |
virtual bool | eventFilter (QObject *, QEvent *) |
Filters events if this object has been installed as an event filter for the watched object. More… | |
template<typename T > | |
T | findChild (const QString &aName=QString()) const |
Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More… | |
template<typename T > | |
QList< T > | findChildren (const QString &aName=QString()) const |
Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More… | |
template<typename T > | |
QList< T > | findChildren (const QRegExp &re) const |
bool | inherits (const char *classname) const |
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More… | |
void | installEventFilter (QObject *) |
Installs an event filter filterObj on this object. More… | |
bool | isWidgetType () const |
Returns true if the object is a widget; otherwise returns false. More… | |
void | killTimer (int id) |
Kills the timer with timer identifier, id. More… | |
virtual const QMetaObject * | metaObject () const |
Returns a pointer to the meta-object of this object. More… | |
void | moveToThread (QThread *thread) |
Changes the thread affinity for this object and its children. More… | |
QString | objectName () const |
QObject * | parent () const |
Returns a pointer to the parent object. More… | |
QVariant | property (const char *name) const |
Returns the value of the object’s name property. More… | |
Q_INVOKABLE | QObject (QObject *parent=0) |
Constructs an object with parent object parent. More… | |
void | removeEventFilter (QObject *) |
Removes an event filter object obj from this object. More… | |
void | setObjectName (const QString &name) |
void | setParent (QObject *) |
Makes the object a child of parent. More… | |
bool | setProperty (const char *name, const QVariant &value) |
Sets the value of the object’s name property to value. More… | |
void | setUserData (uint id, QObjectUserData *data) |
bool | signalsBlocked () const |
Returns true if signals are blocked; otherwise returns false. More… | |
int | startTimer (int interval) |
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More… | |
QThread * | thread () const |
Returns the thread in which the object lives. More… | |
QObjectUserData * | userData (uint id) const |
virtual | ~QObject () |
Destroys the object, deleting all its child objects. More… | |
Static Public Functions |
|
static bool | copy (const QString &fileName, const QString &newName) |
Copies the file fileName to newName. More… | |
static QString | decodeName (const QByteArray &localFileName) |
This does the reverse of QFile::encodeName() using localFileName. More… | |
static QString | decodeName (const char *localFileName) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the Unicode version of the given localFileName. More… | |
static QByteArray | encodeName (const QString &fileName) |
By default, this function converts fileName to the local 8-bit encoding determined by the user’s locale. More… | |
static bool | exists (const QString &fileName) |
Returns true if the file specified by fileName exists; otherwise returns false. More… | |
static bool | link (const QString &oldname, const QString &newName) |
Creates a link named linkName that points to the file fileName. More… | |
static Permissions | permissions (const QString &filename) |
Returns the complete OR-ed together combination of QFile::Permission for fileName. More… | |
static QString | readLink (const QString &fileName) |
Use symLinkTarget() instead. More… | |
static bool | remove (const QString &fileName) |
Removes the file specified by the fileName given. More… | |
static bool | rename (const QString &oldName, const QString &newName) |
Renames the file oldName to newName. More… | |
static bool | resize (const QString &filename, qint64 sz) |
Sets fileName to size (in bytes) sz. More… | |
static void | setDecodingFunction (DecoderFn) |
Sets the function for decoding 8-bit file names. More… | |
static void | setEncodingFunction (EncoderFn) |
Sets the function for encoding Unicode file names. More… | |
static bool | setPermissions (const QString &filename, Permissions permissionSpec) |
Sets the permissions for fileName file to permissions. More… | |
static QString | symLinkTarget (const QString &fileName) |
Returns the absolute path of the file or directory referred to by the symlink (or shortcut on Windows) specified by fileName, or returns an empty string if the fileName does not correspond to a symbolic link. More… | |
Static Public Functions inherited from QObject | |
static bool | connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection) |
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More… | |
static bool | connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection) |
static bool | disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member) |
Disconnects signal in object sender from method in object receiver. More… | |
static bool | disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member) |
static uint | registerUserData () |
static QString | tr (const char *sourceText, const char *comment=0, int n=-1) |
static QString | trUtf8 (const char *sourceText, const char *comment=0, int n=-1) |
Protected Functions |
|
QFile (QFilePrivate &dd, QObject *parent=0) | |
qint64 | readData (char *data, qint64 maxlen) |
Reimplemented Function More… | |
qint64 | readLineData (char *data, qint64 maxlen) |
Reimplemented Function More… | |
qint64 | writeData (const char *data, qint64 len) |
Reimplemented Function More… | |
Protected Functions inherited from QIODevice | |
QIODevice (QIODevicePrivate &dd, QObject *parent=0) | |
void | setErrorString (const QString &errorString) |
Sets the human readable description of the last device error that occurred to str. More… | |
void | setOpenMode (OpenMode openMode) |
Sets the OpenMode of the device to openMode. More… | |
Protected Functions inherited from QObject | |
virtual void | childEvent (QChildEvent *) |
This event handler can be reimplemented in a subclass to receive child events. More… | |
virtual void | connectNotify (const char *signal) |
This virtual function is called when something has been connected to signal in this object. More… | |
virtual void | customEvent (QEvent *) |
This event handler can be reimplemented in a subclass to receive custom events. More… | |
virtual void | disconnectNotify (const char *signal) |
This virtual function is called when something has been disconnected from signal in this object. More… | |
QObject (QObjectPrivate &dd, QObject *parent=0) | |
int | receivers (const char *signal) const |
Returns the number of receivers connected to the signal. More… | |
QObject * | sender () const |
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More… | |
int | senderSignalIndex () const |
virtual void | timerEvent (QTimerEvent *) |
This event handler can be reimplemented in a subclass to receive timer events for the object. More… | |
Additional Inherited Members |
|
Public Slots inherited from QObject | |
void | deleteLater () |
Schedules this object for deletion. More… | |
Signals inherited from QIODevice | |
void | aboutToClose () |
This signal is emitted when the device is about to close. More… | |
void | bytesWritten (qint64 bytes) |
This signal is emitted every time a payload of data has been written to the device. More… | |
void | readChannelFinished () |
This signal is emitted when the input (reading) stream is closed in this device. More… | |
void | readyRead () |
This signal is emitted once every time new data is available for reading from the device. More… | |
Signals inherited from QObject | |
void | destroyed (QObject *=0) |
This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More… | |
Static Public Variables inherited from QObject | |
static const QMetaObject | staticMetaObject |
This variable stores the meta-object for the class. More… | |
Protected Variables inherited from QObject | |
QScopedPointer< QObjectData > | d_ptr |
Static Protected Variables inherited from QObject | |
static const QMetaObject | staticQtMetaObject |
Related Functions inherited from QObject | |
T | qFindChildqFindChildren (const QObject *obj, const QString &name)() |
QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QString &name)() |
QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QRegExp ®Exp)() |
T * | qobject_cast (QObject *object) |
QObjectList | |
void * | qt_find_obj_child (QObject *parent, const char *type, const QString &name) |
Returns a pointer to the object named name that inherits type and with a given parent. More… | |
The QFile class provides an interface for reading from and writing to files.
- Note
- This class or function is reentrant.
QFile is an I/O device for reading and writing text and binary files and The Qt Resource System{resources}. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.
The file name is usually passed in the constructor, but it can be set at any time using setFileName(). QFile expects the file separator to be ‘/’ regardless of operating system. The use of other separators (e.g., ») is not supported.
You can check for a file’s existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)
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 also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.
The size of the file is returned by size(). You can get the current file position using pos(), or move to a new file position using seek(). If you’ve reached the end of the file, atEnd() returns true.
Reading Files Directly
The following example reads a text file line by line:
QFile file(«in.txt»);
return;
while (!file.atEnd()) {
process_line(line);
}
The QIODevice::Text flag passed to open() tells Qt to convert Windows-style line terminators («\r\n») into C++-style terminators («\n»). By default, QFile assumes binary, i.e. it doesn’t perform any conversion on the bytes stored in the file.
Using Streams to Read Files
The next example uses QTextStream to read a text file line by line:
QFile file(«in.txt»);
return;
while (!in.atEnd()) {
QString line = in.readLine();
process_line(line);
}
QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system’s local 8-bit encoding is used (e.g., ISO 8859-1 for most of Europe; see QTextCodec::codecForLocale() for details). This can be changed using setCodec().
To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right:
QFile file(«out.txt»);
return;
out << «The magic number is: « << 49 << «n»;
QDataStream is similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.
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 use standard C++ APIs ( <cstdio> or
<iostream>) or platform-specific APIs to access files instead of QFile, you can use the encodeName() and decodeName() functions to convert between Unicode file names and 8-bit file names.
On Unix, there are some special system files (e.g. in /proc
) for which size() will always return 0, yet you may still be able to read more data from such a file; the data is generated in direct response to you calling read(). In this case, however, you cannot use atEnd() to determine if there is more data to read (since atEnd() will return true for a file that claims to have size 0). Instead, you should either call readAll(), or call read() or readLine() repeatedly until no more data can be read. The next example uses QTextStream to read /proc/modules
line by line:
QFile file(«/proc/modules»);
return;
QString line = in.readLine();
process_line(line);
line = in.readLine();
}
Signals
Unlike other QIODevice implementations, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This implementation detail means that QFile is not suitable for reading and writing certain types of files, such as device files on Unix platforms.
Platform Specific Issues
File permissions are handled differently on Linux/Mac OS X and Windows. In a non writable directory on Linux, files cannot be created. This is not always the case on Windows, where, for instance, the ‘My Documents’ directory usually is not writable, but it is still possible to create files in it.
- See also
- QTextStream, QDataStream, QFileInfo, QDir, {The Qt Resource System}
Definition at line 65 of file qfile.h.
◆ DecoderFn
◆ EncoderFn
◆ FileError
This enum describes the errors that may be returned by the error() function.
- NoError No error occurred.
- ReadError An error occurred when reading from the file.
- WriteError An error occurred when writing to the file.
- FatalError A fatal error occurred.
- ResourceError
- OpenError The file could not be opened.
- AbortError The operation was aborted.
- TimeOutError A timeout occurred.
- UnspecifiedError An unspecified error occurred.
- RemoveError The file could not be removed.
- RenameError The file could not be renamed.
- PositionError The position in the file could not be changed.
- ResizeError The file could not be resized.
- PermissionsError The file could not be accessed.
- CopyError The file could not be copied.
- ConnectError
Enumerator | |
---|---|
NoError | |
ReadError | |
WriteError | |
FatalError | |
ResourceError | |
OpenError | |
AbortError | |
TimeOutError | |
UnspecifiedError | |
RemoveError | |
RenameError | |
PositionError | |
ResizeError | |
PermissionsError | |
CopyError |
Definition at line 74 of file qfile.h.
74 {
90 #ifdef QT3_SUPPORT
91 , ConnectError = 30
92 #endif
93 };
◆ FileHandleFlag
This enum is used when opening a file to specify additional options which only apply to files and not to a generic QIODevice.
- Since
- 4.8
- AutoCloseHandle The file handle passed into open() should be closed by close(), the default behaviour is that close just flushes the file and the application is responsible for closing the file handle. When opening a file by name, this flag is ignored as Qt always «owns» the file handle and must close it.
- DontCloseHandle The file handle passed into open() will not be closed by Qt. The application must ensure that close() is called.
Enumerator | |
---|---|
AutoCloseHandle | |
DontCloseHandle |
Definition at line 103 of file qfile.h.
◆ MemoryMapFlags
This enum describes special options that may be used by the map() function.
- Since
- 4.4
- NoOptions No options.
Enumerator | |
---|---|
NoOptions |
Definition at line 180 of file qfile.h.
◆ Permission
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.
- ReadOwner The file is readable by the owner of the file.
- WriteOwner The file is writable by the owner of the file.
- ExeOwner The file is executable by the owner of the file.
- ReadUser The file is readable by the user.
- WriteUser The file is writable by the user.
- ExeUser The file is executable by the user.
- ReadGroup The file is readable by the group.
- WriteGroup The file is writable by the group.
- ExeGroup The file is executable by the group.
- ReadOther The file is readable by anyone.
- WriteOther The file is writable by anyone.
- ExeOther The file is executable by anyone.
- Warning
- Because of differences in the platforms supported by Qt, the semantics of ReadUser, WriteUser and ExeUser are platform-dependent: 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.
Note that Qt does not by default check for permissions on NTFS file systems, as this may decrease the performance of file handling considerably. It is possible to force permission checking on NTFS by including the following code in your source:
Permission checking is then turned on and off by incrementing and decrementing qt_ntfs_permission_lookup
by 1.
Enumerator | |
---|---|
ReadOwner | |
WriteOwner | |
ExeOwner | |
ReadUser | |
WriteUser | |
ExeUser | |
ReadGroup | |
WriteGroup | |
ExeGroup | |
ReadOther | |
WriteOther | |
ExeOther |
Definition at line 95 of file qfile.h.
◆ QFile() [1/5]
◆ QFile() [2/5]
QFile::QFile | ( | const QString & | name | ) |
Constructs a new file object to represent the file with the given name.
Definition at line 431 of file qfile.cpp.
433 {
435 d->fileName = name;
436 }
The QFile class provides an interface for reading from and writing to files.
QIODevice()
Constructs a QIODevice object.
◆ QFile() [3/5]
|
explicit |
Constructs a new file object with the given parent.
Definition at line 424 of file qfile.cpp.
426 {
427 }
QIODevice()
Constructs a QIODevice object.
Constructs a new file object with the given parent to represent the file with the specified name.
Definition at line 441 of file qfile.cpp.
443 {
445 d->fileName = name;
446 }
The QFile class provides an interface for reading from and writing to files.
QIODevice()
Constructs a QIODevice object.
◆ ~QFile()
Destroys the file object, closing it if necessary.
Definition at line 459 of file qfile.cpp.
460 {
462 }
virtual void close()
Calls QFile::flush() and closes the file.
◆ QFile() [5/5]
- Warning
- This function is not part of the public interface.
Definition at line 450 of file qfile.cpp.
452 {
453 }
QIODevice()
Constructs a QIODevice object.
◆ atEnd()
|
virtual |
Returns true if the end of the file has been reached; otherwise returns false.
For regular empty files on Unix (e.g. those in /proc
), this function returns true, since the file system reports that the size of such a file is 0. Therefore, you should not depend on atEnd() when reading data from such a file, but rather call read() until no more data can be read.
Reimplemented from QIODevice.
Definition at line 1735 of file qfile.cpp.
Referenced by copy(), QBenchmarkValgrindUtils::extractResult(), fontFile(), QHostInfo::localDomainName(), qt_parseEtcLpPrinters(), qt_parseNsswitchConf(), qt_parsePrintcap(), qt_parsePrintersConf(), and QCoreApplicationData::~QCoreApplicationData().
1736 {
1738
1739
1740 if (!d->buffer.isEmpty())
1741 return false;
1742
1744 return true;
1745
1746 if (!d->ensureFlushed())
1747 return false;
1748
1749
1751
1752
1753 return d->fileEngine->atEnd();
1754 }
1755
1756
1757
1758 if (pos() < d->cachedSize)
1759 return false;
1760
1761
1763 }
bool isOpen() const
Returns true if the device is open; otherwise returns false.
qint64 pos() const
Reimplemented Function
The QFile class provides an interface for reading from and writing to files.
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
◆ close()
|
virtual |
Calls QFile::flush() and closes the file.
Errors from flush are ignored.
- See also
- QIODevice::close()
Reimplemented from QIODevice.
Definition at line 1680 of file qfile.cpp.
Referenced by QNetworkManagerEngine::bytesReceived(), QConnmanEngine::bytesReceived(), QNetworkManagerEngine::bytesWritten(), QConnmanEngine::bytesWritten(), QUnixPrintWidgetPrivate::checkFields(), QNetworkAccessFileBackend::closeDownstreamChannel(), QMacPasteboardMimeVCard::convertFromMime(), copy(), QTemporaryFile::createLocalFile(), QNetworkDiskCache::data(), QGraphicsAnchorLayoutPrivate::dumpGraph(), QPdfEnginePrivate::embedFont(), QtopiaPrintEngine::end(), QZipReader::extractAll(), QNetworkDiskCache::fileMetaData(), fontPath(), QDirectFBPixmapData::fromFile(), QGLPixmapData::fromFile(), QTransportAuthPrivate::getClientKey(), QScriptEngine::importExtension(), QAxScriptManager::load(), QTextBrowser::loadResource(), QTextDocument::loadResource(), QPictureIO::pictureFormat(), qt_parse_pattern(), QPictureIO::read(), registerFont(), remove(), rename(), setFileName(), QSslSocketBackendPrivate::startHandshake(), QNetworkAccessFileBackend::uploadReadyReadSlot(), QPictureIO::write(), QCoreApplicationData::~QCoreApplicationData(), ~QFile(), and QTemporaryFile::~QTemporaryFile().
1681 {
1684 return;
1685 bool flushed = flush();
1687
1688
1689 d->lastWasWrite = false;
1690 d->writeBuffer.clear();
1691
1692
1693 if (d->fileEngine->close() && flushed)
1695 else if (flushed)
1696 d->setError(d->fileEngine->error(), d->fileEngine->errorString());
1697 }
virtual void close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
bool isOpen() const
Returns true if the device is open; otherwise returns false.
bool flush()
Flushes any buffered data to the file.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
◆ copy() [1/2]
bool QFile::copy | ( | const QString & | newName | ) |
Copies the file currently specified by fileName() to a file called newName.
Returns true if successful; otherwise returns false.
Note that if a file with the name newName already exists, copy() returns false (i.e. QFile will not overwrite it).
The source file is closed before it is copied.
- See also
- setFileName()
Definition at line 926 of file qfile.cpp.
Referenced by QDragManager::drag(), QDirModel::dropMimeData(), and QFileSystemModel::dropMimeData().
927 {
929 if (d->fileName.isEmpty()) {
930 qWarning(«QFile::copy: Empty or null file name»);
931 return false;
932 }
934
935
936
938 return false;
939 }
945 return true;
946 } else {
947 bool error = false;
949 error = true;
950 d->setError(QFile::CopyError, tr(«Cannot open %1 for input»).arg(d->fileName));
951 } else {
953 #ifdef QT_NO_TEMPORARYFILE
956 error = true;
957 #else
959 if (!out.open()) {
961 if (!out.open())
962 error = true;
963 }
964 #endif
965 if (error) {
966 out.close();
969 } else {
970 char block[4096];
971 qint64 totalRead = 0;
972 while(!atEnd()) {
973 qint64 in = read(block, sizeof(block));
974 if (in <= 0)
975 break;
976 totalRead += in;
977 if(in != out.write(block, in)) {
980 error = true;
981 break;
982 }
983 }
984
985 if (totalRead != size()) {
986
987
988 error = true;
989 }
990 if (!error && !out.rename(newName)) {
991 error = true;
993 d->setError(QFile::CopyError, tr(«Cannot create %1 for output»).arg(newName));
994 }
995 #ifdef QT_NO_TEMPORARYFILE
996 if (error)
997 out.remove();
998 #else
999 if (!error)
1000 out.setAutoRemove(false);
1001 #endif
1002 }
1003 }
1004 if(!error) {
1008 return true;
1009 }
1010 }
1011 }
1012 return false;
1013 }
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
The QTemporaryFile class is an I/O device that operates on temporary files.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read…
bool exists() const
Returns true if the file specified by fileName() exists; otherwise returns false. …
Q_CORE_EXPORT void qWarning(const char *,…)
qint64 size() const
Returns the size of the file.
static QString tempPath()
Returns the absolute path of the system's temporary directory.
void unsetError()
Sets the file's error to QFile::NoError.
QString arg(qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(‘ ‘)) const Q_REQUIRED_RESULT
The QFile class provides an interface for reading from and writing to files.
bool setPermissions(Permissions permissionSpec)
Sets the permissions for the file to the permissions specified.
bool copy(const QString &newName)
Copies the file currently specified by fileName() to a file called newName.
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
void setFileTemplate(const QString &name)
Sets the static portion of the file name to name.
FileError error() const
Returns the file error status.
The QFileInfo class provides system-independent file information.
bool atEnd() const
Returns true if the end of the file has been reached; otherwise returns false.
virtual void close()
Calls QFile::flush() and closes the file.
◆ copy() [2/2]
|
static |
Copies the file fileName to newName.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Returns true if successful; otherwise returns false.
If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).
- See also
- rename()
Definition at line 1031 of file qfile.cpp.
1032 {
1033 return QFile(fileName).copy(newName);
1034 }
◆ decodeName() [1/2]
This does the reverse of QFile::encodeName() using localFileName.
- See also
- setDecodingFunction(), encodeName()
Definition at line 552 of file qfile.cpp.
Referenced by QCoreApplication::applicationFilePath(), QFontEngineQPF::cleanUpAfterClientCrash(), QWSServerPrivate::cleanupFonts(), QZipReader::extractAll(), QFileSystemEngine::getLinkTarget(), QFileSystemEngine::homePath(), QGuiPlatformPlugin::iconThemeSearchPaths(), initDefaultPaths(), loadSingleEngine(), QHostInfo::localDomainName(), QFontEngineQPF::QFontEngineQPF(), QFileSystemEntry::resolveFilePath(), QFileSystemEngine::resolveGroupName(), QFileSystemEngine::resolveUserName(), and QFileSystemEngine::tempPath().
553 {
555 }
static QFile::DecoderFn decoder
◆ decodeName() [2/2]
|
inlinestatic |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the Unicode version of the given localFileName.
See encodeName() for details.
Definition at line 127 of file qfile.h.
The QByteArray class provides an array of bytes.
static QString decodeName(const QByteArray &localFileName)
This does the reverse of QFile::encodeName() using localFileName.
◆ encodeName()
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() setEncodingFunction()
Definition at line 528 of file qfile.cpp.
Referenced by QProcessPrivate::_q_notified(), QInotifyFileSystemWatcherEngine::addPaths(), QKqueueFileSystemWatcherEngine::addPaths(), QZipWriter::addSymLink(), QSharedMemoryPrivate::attach(), QSystemSemaphorePrivate::cleanHandle(), QFontEngineQPF::cleanUpAfterClientCrash(), QSharedMemoryPrivate::create(), QProcessPrivate::createChannel(), QFileSystemEngine::createDirectory(), QSharedMemoryPrivate::createUnixKeyFile(), QSharedMemoryPrivate::detach(), QTranslatorPrivate::do_load(), QFileSystemEngine::getLinkTarget(), QSystemSemaphorePrivate::handle(), QSharedMemoryPrivate::handle(), initializeDb(), QLibraryPrivate::isPlugin(), QLibraryPrivate::load_sys(), QFileDialogPrivate::maxNameLength(), QSQLite2Driver::open(), QWSSoundServerPrivate::openFile(), QBasicUnixFontDatabase::populateFontDatabase(), QPlatformFontDatabase::populateFontDatabase(), QFontEngineQPA::QFontEngineQPA(), QFontEngineQPF::QFontEngineQPF(), QFontEngineQPF1::QFontEngineQPF1(), qt_parse_pattern(), registerFont(), QDynamicFileResourceRoot::registerSelf(), QFileSystemEngine::removeDirectory(), QFileSystemEntry::resolveNativeFilePath(), QPluginLoader::setFileName(), QProcessPrivate::startDetached(), and QProcessPrivate::startProcess().
529 {
531 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
static QFile::EncoderFn encoder
◆ error()
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.
- See also
- unsetError()
Definition at line 1984 of file qfile.cpp.
Referenced by copy(), QIODevice::errorString(), fontPath(), QPdfBaseEngine::newPage(), QZipReader::QZipReader(), QZipWriter::QZipWriter(), QNetworkAccessFileBackend::readMoreFromFile(), remove(), rename(), and QNetworkDiskCachePrivate::storeItem().
1985 {
1987 return d->error;
1988 }
The QFile class provides an interface for reading from and writing to files.
◆ exists() [1/2]
bool QFile::exists | ( | ) | const |
Returns true if the file specified by fileName() exists; otherwise returns false.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
- See also
- fileName(), setFileName()
Definition at line 626 of file qfile.cpp.
Referenced by QFileDialogPrivate::_q_createDirectory(), QDeclarativeImportDatabase::addImportPath(), QDeclarativeImportDatabase::addPluginPath(), QCoreApplicationPrivate::appendApplicationPathToLibraryPaths(), QNetworkManagerEngine::bytesReceived(), QConnmanEngine::bytesReceived(), QNetworkManagerEngine::bytesWritten(), QConnmanEngine::bytesWritten(), QMacPasteboardMimeVCard::convertFromMime(), copy(), QSharedMemoryPrivate::createUnixKeyFile(), QZipWriter::exists(), QZipReader::exists(), QDir::exists(), QZipReader::extractAll(), QLibraryInfoPrivate::findConfiguration(), fontPath(), QDirectFBPixmapData::fromFile(), QDirectFbBlitterPlatformPixmap::fromFile(), QTransportAuthPrivate::getClientKey(), QGtkStylePrivate::getThemeName(), QSharedMemoryPrivate::handle(), QAxBase::initialize(), initializeDb(), isDirPath(), launchWebBrowser(), QCoreApplication::libraryPaths(), QLibraryPrivate::load_sys(), QFontDatabasePrivate::loadFromCache(), loadSingleEngine(), QNetworkAccessFileBackend::open(), QBasicUnixFontDatabase::populateFontDatabase(), QPlatformFontDatabase::populateFontDatabase(), QIconTheme::QIconTheme(), qmlsqldatabase_open_sync(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QDynamicFileResourceRoot::registerSelf(), rename(), QDir::rename(), QNetworkDiskCachePrivate::storeItem(), QConfFileSettingsPrivate::syncConfFile(), QFileDialogPrivate::typedFiles(), and QAxFactory::validateLicenseKey().
627 {
628
631 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
FileFlag
The permissions and types of a file, suitable for OR'ing together.
◆ exists() [2/2]
|
static |
Returns true if the file specified by fileName exists; otherwise returns false.
Definition at line 639 of file qfile.cpp.
640 {
642 }
bool exists() const
Returns true if the file exists; otherwise returns false.
The QFileInfo class provides system-independent file information.
◆ fileEngine()
Returns the QIOEngine for this QFile object.
- Warning
- This function is not part of the public interface.
Reimplemented in QTemporaryFile.
Definition at line 1965 of file qfile.cpp.
Referenced by QFontDatabase::addApplicationFont(), copy(), QTemporaryFile::createLocalFile(), exists(), fileName(), QFreetypeFace::getFace(), link(), map(), open(), permissions(), readLink(), remove(), rename(), resize(), setPermissions(), size(), and unmap().
1966 {
1968 if(!d->fileEngine)
1970 return d->fileEngine;
1971 }
static QAbstractFileEngine * create(const QString &fileName)
Creates and returns a QAbstractFileEngine suitable for processing fileName.
The QFile class provides an interface for reading from and writing to files.
◆ fileName()
Returns the name set by setFileName() or to the QFile constructors.
- See also
- setFileName(), QFileInfo::fileName()
Definition at line 470 of file qfile.cpp.
Referenced by __fileOpen(), QMacPasteboardMimeVCard::convertFromMime(), QGraphicsAnchorLayoutPrivate::dumpGraph(), encodeName(), QTextDocumentWriter::fileName(), QImageWriter::fileName(), QImageReader::fileName(), QImageReaderPrivate::initHandler(), QFontDatabasePrivate::loadFromCache(), QTemporaryFile::open(), open(), QIconTheme::QIconTheme(), QIODevice::QIODevice(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QCacheItem::read(), registerFont(), QFileInfo::setFile(), setFileName(), and QConfFileSettingsPrivate::syncConfFile().
471 {
473 }
virtual QString fileName(FileName file=DefaultName) const
Return the file engine's current file name in the format specified by file.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
◆ flush()
Flushes any buffered data to the file.
Returns true if successful; otherwise returns false.
Definition at line 1645 of file qfile.cpp.
Referenced by close(), QTextStreamPrivate::flushWriteBuffer(), registerFont(), QNetworkAccessFileBackend::uploadReadyReadSlot(), and writeData().
1646 {
1648 if (!d->fileEngine) {
1649 qWarning(«QFile::flush: No file engine. Is IODevice open?»);
1650 return false;
1651 }
1652
1653 if (!d->writeBuffer.isEmpty()) {
1659 d->setError(err, d->fileEngine->errorString());
1660 return false;
1661 }
1662 }
1663
1664 if (!d->fileEngine->flush()) {
1668 d->setError(err, d->fileEngine->errorString());
1669 return false;
1670 }
1671 return true;
1672 }
static qint64 _qfile_writeData(QAbstractFileEngine *engine, QRingBuffer *buffer)
Q_CORE_EXPORT void qWarning(const char *,…)
qint64 size() const
Returns the size of the file.
The QFile class provides an interface for reading from and writing to files.
FileError
This enum describes the errors that may be returned by the error() function.
◆ handle()
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.
This function is not supported on Windows CE.
On Symbian, this function returns -1 if the file was opened normally, as Symbian OS native file handles do not fit in an int, and are incompatible with C library functions that the handle would be used for. If the file was opened using the overloads that take an open C library file handle / file descriptor, then this function returns that same handle.
- See also
- QSocketNotifier
Definition at line 1419 of file qfile.cpp.
Referenced by QTextStreamPrivate::fillReadBuffer(), QPatternist::ColorOutputPrivate::isColoringPossible(), and QConfFileSettingsPrivate::syncConfFile().
1420 {
1422 if (!isOpen() || !d->fileEngine)
1423 return -1;
1424
1425 return d->fileEngine->handle();
1426 }
bool isOpen() const
Returns true if the device is open; otherwise returns false.
The QFile class provides an interface for reading from and writing to files.
◆ isSequential()
|
virtual |
Returns true if the file can only be manipulated sequentially; otherwise returns false.
Most files support random-access, but some special files may not.
- See also
- QIODevice::isSequential()
Reimplemented from QIODevice.
Definition at line 1044 of file qfile.cpp.
Referenced by QFilePrivate::putCharHelper(), and rename().
1045 {
1047 return d->fileEngine && d->fileEngine->isSequential();
1048 }
The QFile class provides an interface for reading from and writing to files.
◆ link() [1/2]
bool QFile::link | ( | const QString & | linkName | ) |
Creates a link named linkName that points to the file currently specified by fileName().
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.
This function will not overwrite an already existing entity in the file system; in this case, link()
will return false and set QFile::error() to return QFile::RenameError.
- Note
- To create a valid link on Windows, linkName must have a
.lnk
file extension. - Symbian filesystem does not support links.
- See also
- setFileName()
Definition at line 877 of file qfile.cpp.
Referenced by QDirModel::dropMimeData(), QFileSystemModel::dropMimeData(), and QZipReader::extractAll().
878 {
880 if (d->fileName.isEmpty()) {
881 qWarning(«QFile::link: Empty or null file name»);
882 return false;
883 }
887 return true;
888 }
890 return false;
891 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Q_CORE_EXPORT void qWarning(const char *,…)
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
The QFileInfo class provides system-independent file information.
bool link(const QString &newName)
Creates a link named linkName that points to the file currently specified by fileName().
◆ link() [2/2]
|
static |
Creates a link named linkName that points to the file fileName.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
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()
Definition at line 908 of file qfile.cpp.
909 {
910 return QFile(fileName).link(linkName);
911 }
◆ map()
Maps size bytes of the file into memory starting at offset.
- Since
- 4.4 A file should be open for a map to succeed but the file does not need to stay open after the memory has been mapped. When the QFile is destroyed or a new file is opened with this object, any maps that have not been unmapped will automatically be unmapped.
Any mapping options can be passed through flags.
Returns a pointer to the memory or 0 if there is an error.
- Note
- On Windows CE 5.0 the file will be closed before mapping occurs.
- See also
- unmap(), QAbstractFileEngine::supportsExtension()
Definition at line 1460 of file qfile.cpp.
Referenced by QNetworkDiskCache::data(), and qt_parse_pattern().
1461 {
1466 uchar *address = d->fileEngine->map(offset, size, flags);
1467 if (address == 0)
1468 d->setError(d->fileEngine->error(), d->fileEngine->errorString());
1469 return address;
1470 }
1471 return 0;
1472 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
qint64 size() const
Returns the size of the file.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
◆ open() [1/5]
|
virtual |
Opens the file using OpenMode mode, returning true if successful; otherwise false.
The mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered.
- Note
- In QIODevice::WriteOnly or QIODevice::ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it.
- See also
- QIODevice::OpenMode, setFileName()
Reimplemented from QIODevice.
Reimplemented in QTemporaryFile.
Definition at line 1064 of file qfile.cpp.
Referenced by __fileOpen(), QFontDatabase::addApplicationFont(), QTransportAuth::authorizeRequest(), QNetworkManagerEngine::bytesReceived(), QConnmanEngine::bytesReceived(), QNetworkManagerEngine::bytesWritten(), QConnmanEngine::bytesWritten(), QUnixPrintWidgetPrivate::checkFields(), QPatternist::ColorOutputPrivate::ColorOutputPrivate(), compileSource(), QGLShader::compileSourceFile(), QMacPasteboardMimeVCard::convertFromMime(), copy(), QTemporaryFile::createLocalFile(), createPixmapDataSync(), QUuid::createUuid(), QNetworkDiskCache::data(), QTranslatorPrivate::do_load(), QGraphicsAnchorLayoutPrivate::dumpGraph(), DumpIDL(), dumpOutput(), QPdfEnginePrivate::embedFont(), QtopiaPrintEngine::end(), QZipReader::extractAll(), QBenchmarkValgrindUtils::extractResult(), QNetworkDiskCache::fileMetaData(), fontFile(), fontPath(), QDirectFBPixmapData::fromFile(), QGLPixmapData::fromFile(), QSslCertificate::fromPath(), QFreetypeFace::getFace(), QGtkStylePrivate::getThemeName(), QImageReader::imageFormat(), QScriptEngine::importExtension(), QDeclarativeInclude::include(), QCss::Parser::init(), QImageReaderPrivate::initHandler(), initializeDb(), QConfFile::isWritable(), launchWebBrowser(), QPicture::load(), QSvgTinyDocument::load(), QDeclarativeBorderImage::load(), QDeclarativeDataLoader::load(), QAxScriptManager::load(), QFontDatabasePrivate::loadFromCache(), QRawFont::loadFromFile(), QWSKbPrivate::loadKeymap(), QTextBrowser::loadResource(), QTextDocument::loadResource(), QScriptDebuggerConsolePrivate::loadScriptedCommands(), QHostInfo::localDomainName(), FAREnforcer::logAuthAttempt(), QNetworkAccessFileBackend::open(), QTemporaryFile::open(), open(), QFileOpenEvent::openFile(), QPdfBaseEnginePrivate::openPrintDevice(), operator<<(), QDeclarativeDirParser::parse(), QPatternist::XsdSchemaParser::parseImport(), QPictureIO::pictureFormat(), QDeclarativePixmapReader::processJob(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), qt_getDefaultFromHomePrinters(), qt_getLprPrinters(), qt_parse_pattern(), qt_parseEtcLpPrinters(), qt_parseNsswitchConf(), qt_parsePrintcap(), qt_parsePrintersConf(), qt_parseQconfig(), QTextStream::QTextStream(), QZipReader::QZipReader(), QZipWriter::QZipWriter(), QPictureIO::read(), QWSCalibratedMouseHandler::readCalibration(), readConf(), readSourceFile(), registerFont(), QDynamicFileResourceRoot::registerSelf(), rename(), runningUnderDebugger(), QPicture::save(), QWaylandSelection::send(), QSslSocket::setLocalCertificate(), QSslSocket::setPrivateKey(), QTransportAuth::setProcessKey(), QSslSocketBackendPrivate::startHandshake(), QConfFileSettingsPrivate::syncConfFile(), QDeclarativeInclude::worker_include(), QSvgIconEngine::write(), QPictureIO::write(), QWSCalibratedMouseHandler::writeCalibration(), writeIncludeFile(), QCoreApplicationData::~QCoreApplicationData(), and QTraceWindowSurface::~QTraceWindowSurface().
1065 {
1069 return false;
1070 }
1073
1076 qWarning(«QIODevice::open: File access not specified»);
1077 return false;
1078 }
1079
1080 #ifdef Q_OS_SYMBIAN
1081
1083 #else
1084
1086 #endif
1087 {
1089 if (mode & Append) {
1090
1091
1093 }
1094 return true;
1095 }
1099 d->setError(err, d->fileEngine->errorString());
1100 return false;
1101 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
bool isOpen() const
Returns true if the device is open; otherwise returns false.
virtual bool seek(qint64 pos)
Sets the file position to the given offset.
Q_CORE_EXPORT void qWarning(const char *,…)
qint64 size() const
Returns the size of the file.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
FileError
This enum describes the errors that may be returned by the error() function.
#define qPrintable(string)
◆ open() [2/5]
bool QFile::open | ( | FILE * | fh, |
OpenMode | mode | ||
) |
Opens the existing file handle fh in the given mode.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Returns true if successful; otherwise returns false.
Example:
#include <stdio.h>
void printError(const char* msg)
{
file.write(msg, qstrlen(msg));
}
When a QFile is opened using this function, close() does not actually close the file, but only flushes it.
Warning:
-
If fh does not refer to a regular file, e.g., it is
stdin
,stdout
, orstderr
, you may not be able to seek(). size() returns0
in those cases. See QIODevice::isSequential() for more information. - Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
- Note
- For Windows CE you may not be able to call resize().
- See also
- close(), {qmake Variable Reference::CONFIG}{qmake Variable Reference}
Note for the Windows Platform
fh must be opened in binary mode (i.e., the mode string must contain ‘b’, as in «rb» or «wb») when accessing files and other random-access devices. Qt will translate the end-of-line characters if you pass QIODevice::Text to mode. Sequential devices, such as stdin and stdout, are unaffected by this limitation.
You need to enable support for console applications in order to use the stdin, stdout and stderr streams at the console. To do this, add the following declaration to your application’s project file:
Definition at line 1152 of file qfile.cpp.
1153 {
1155 }
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
◆ open() [3/5]
bool QFile::open | ( | int | fd, |
OpenMode | mode | ||
) |
Opens the existing file descriptor fd in the given mode.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
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 not a regular file, e.g, it is 0 (
stdin
), 1 (stdout
), or 2 (stderr
), you may not be able to seek(). In those cases, size() returns0
. See QIODevice::isSequential() for more information. -
For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() returns
0
. - Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
- See also
- close()
Definition at line 1270 of file qfile.cpp.
1271 {
1273 }
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
◆ open() [4/5]
bool QFile::open | ( | FILE * | fh, |
OpenMode | mode, | ||
FileHandleFlags | handleFlags | ||
) |
Opens the existing file handle fh in the given mode.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Returns true if successful; otherwise returns false.
Example:
#include <stdio.h>
void printError(const char* msg)
{
file.write(msg, qstrlen(msg));
}
When a QFile is opened using this function, behaviour of close() is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified, and this function succeeds, then calling close() closes the adopted handle. Otherwise, close() does not actually close the file, but only flushes it.
Warning:
-
If fh does not refer to a regular file, e.g., it is
stdin
,stdout
, orstderr
, you may not be able to seek(). size() returns0
in those cases. See QIODevice::isSequential() for more information. - Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
- Note
- For Windows CE you may not be able to call resize().
- See also
- close(), {qmake Variable Reference::CONFIG}{qmake Variable Reference}
Note for the Windows Platform
fh must be opened in binary mode (i.e., the mode string must contain ‘b’, as in «rb» or «wb») when accessing files and other random-access devices. Qt will translate the end-of-line characters if you pass QIODevice::Text to mode. Sequential devices, such as stdin and stdout, are unaffected by this limitation.
You need to enable support for console applications in order to use the stdin, stdout and stderr streams at the console. To do this, add the following declaration to your application’s project file:
Definition at line 1203 of file qfile.cpp.
1204 {
1208 return false;
1209 }
1214 qWarning(«QFile::open: File access not specified»);
1215 return false;
1216 }
1217 if (d->openExternalFile(mode, fh, handleFlags)) {
1219 if (mode & Append) {
1221 } else {
1223 if (pos != -1)
1225 }
1226 return true;
1227 }
1228 return false;
1229 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Q_CORE_EXPORT void qWarning(const char *,…)
qint64 pos() const
Reimplemented Function
qint64 size() const
Returns the size of the file.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
#define qPrintable(string)
bool seek(qint64 offset)
For random-access devices, this function sets the current position to pos, returning true on success…
◆ open() [5/5]
bool QFile::open | ( | int | fd, |
OpenMode | mode, | ||
FileHandleFlags | handleFlags | ||
) |
Opens the existing file descriptor fd in the given mode.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Returns true if successful; otherwise returns false.
When a QFile is opened using this function, behaviour of close() is controlled by the handleFlags argument. If AutoCloseHandle is specified, and this function succeeds, then calling close() closes the adopted handle. Otherwise, close() does not actually close the file, but only flushes it.
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 not a regular file, e.g, it is 0 (
stdin
), 1 (stdout
), or 2 (stderr
), you may not be able to seek(). In those cases, size() returns0
. See QIODevice::isSequential() for more information. -
For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() returns
0
. - Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
- See also
- close()
Definition at line 1308 of file qfile.cpp.
1309 {
1313 return false;
1314 }
1319 qWarning(«QFile::open: File access not specified»);
1320 return false;
1321 }
1322 if (d->openExternalFile(mode, fd, handleFlags)) {
1324 if (mode & Append) {
1326 } else {
1327 qint64 pos = (qint64)QT_LSEEK(fd, QT_OFF_T(0), SEEK_CUR);
1328 if (pos != -1)
1330 }
1331 return true;
1332 }
1333 return false;
1334 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Q_CORE_EXPORT void qWarning(const char *,…)
qint64 pos() const
Reimplemented Function
qint64 size() const
Returns the size of the file.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
#define qPrintable(string)
bool seek(qint64 offset)
For random-access devices, this function sets the current position to pos, returning true on success…
◆ permissions() [1/2]
QFile::Permissions QFile::permissions | ( | ) | const |
◆ permissions() [2/2]
|
static |
Returns the complete OR-ed together combination of QFile::Permission for fileName.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Definition at line 1591 of file qfile.cpp.
1592 {
1593 return QFile(fileName).permissions();
1594 }
◆ pos()
|
virtual |
◆ readData()
|
protectedvirtual |
Reimplemented Function
Implements QIODevice.
Definition at line 1839 of file qfile.cpp.
1840 {
1843 if (!d->ensureFlushed())
1844 return -1;
1845
1847 if(read < 0) {
1851 d->setError(err, d->fileEngine->errorString());
1852 }
1853
1854 if (read < len) {
1855
1856 d->cachedSize = 0;
1857 }
1858
1859 return read;
1860 }
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read…
static const char * data(const QByteArray &arr)
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
FileError
This enum describes the errors that may be returned by the error() function.
◆ readLineData()
|
protectedvirtual |
Reimplemented Function
Reimplemented from QIODevice.
Definition at line 1812 of file qfile.cpp.
1813 {
1815 if (!d->ensureFlushed())
1816 return -1;
1817
1820 read = d->fileEngine->readLine(data, maxlen);
1821 } else {
1822
1823
1825 }
1826
1827 if (read < maxlen) {
1828
1829 d->cachedSize = 0;
1830 }
1831
1832 return read;
1833 }
virtual qint64 readLineData(char *data, qint64 maxlen)
Reads up to maxSize characters into data and returns the number of characters read.
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read…
static const char * data(const QByteArray &arr)
The QFile class provides an interface for reading from and writing to files.
◆ readLink() [1/2]
Use symLinkTarget() instead.
Definition at line 671 of file qfile.cpp.
672 {
674 }
virtual QString fileName(FileName file=DefaultName) const
Return the file engine's current file name in the format specified by file.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
◆ readLink() [2/2]
Use symLinkTarget() instead.
Definition at line 700 of file qfile.cpp.
701 {
703 }
QString readLink() const
Use symLinkTarget() instead.
The QFileInfo class provides system-independent file information.
◆ remove() [1/2]
Removes the file specified by fileName().
Returns true if successful; otherwise returns false.
The file is closed before it is removed.
- See also
- setFileName()
Definition at line 715 of file qfile.cpp.
Referenced by QUnixPrintWidgetPrivate::checkFields(), QSystemSemaphorePrivate::cleanHandle(), QBenchmarkValgrindUtils::cleanup(), QFontEngineQPF::cleanUpAfterClientCrash(), QWSServerPrivate::cleanupFonts(), QPdfBaseEnginePrivate::closePrintDevice(), QSharedMemoryPrivate::create(), QSharedMemoryPrivate::detach(), QDirModel::dropMimeData(), DumpIDL(), QNetworkDiskCache::expire(), initializeDb(), QTransportAuth::isDiscoveryMode(), registerFont(), QFileSystemModel::remove(), QDir::remove(), QNetworkDiskCachePrivate::removeFile(), rename(), and QNetworkDiskCachePrivate::storeItem().
716 {
718 if (d->fileName.isEmpty()) {
719 qWarning(«QFile::remove: Empty or null file name»);
720 return false;
721 }
727 return true;
728 }
730 }
731 return false;
732 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
Q_CORE_EXPORT void qWarning(const char *,…)
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
FileError error() const
Returns the file error status.
virtual void close()
Calls QFile::flush() and closes the file.
◆ remove() [2/2]
|
static |
Removes the file specified by the fileName given.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Returns true if successful; otherwise returns false.
- See also
- remove()
Definition at line 748 of file qfile.cpp.
749 {
750 return QFile(fileName).remove();
751 }
◆ rename() [1/2]
bool QFile::rename | ( | const QString & | newName | ) |
Renames the file currently specified by fileName() to newName.
Returns true if successful; otherwise returns false.
If a file with the name newName already exists, rename() returns false (i.e., QFile will not overwrite it).
The file is closed before it is renamed.
- See also
- setFileName()
Definition at line 766 of file qfile.cpp.
Referenced by QDragManager::drag(), QFileSystemModel::dropMimeData(), initializeDb(), QDir::rename(), and QNetworkDiskCachePrivate::storeItem().
767 {
769 if (d->fileName.isEmpty()) {
770 qWarning(«QFile::rename: Empty or null file name»);
771 return false;
772 }
774
775
776
778 return false;
779 }
785
786 d->fileEngine->setFileName(newName);
787 d->fileName = newName;
788 return true;
789 }
790
792 d->setError(QFile::RenameError, tr(«Will not rename sequential file using block copy»));
793 return false;
794 }
795
796 QFile out(newName);
799 bool error = false;
800 char block[4096];
802 while ((bytes = read(block, sizeof(block))) > 0) {
803 if (bytes != out.write(block, bytes)) {
805 error = true;
806 break;
807 }
808 }
809 if (bytes == -1) {
811 error = true;
812 }
813 if(!error) {
814 if (!remove()) {
816 error = true;
817 }
818 }
819 if (error) {
820 out.remove();
821 } else {
822 d->fileEngine->setFileName(newName);
826 }
829 }
831 }
833 }
834 return false;
835 }
bool rename(const QString &newName)
Renames the file currently specified by fileName() to newName.
bool isSequential() const
Returns true if the file can only be manipulated sequentially; otherwise returns false.
bool open(OpenMode flags)
Opens the file using OpenMode mode, returning true if successful; otherwise false.
QString errorString() const
Returns a human-readable description of the last device error that occurred.
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read…
bool exists() const
Returns true if the file specified by fileName() exists; otherwise returns false. …
Q_CORE_EXPORT void qWarning(const char *,…)
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
bool setPermissions(Permissions permissionSpec)
Sets the permissions for the file to the permissions specified.
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
FileError error() const
Returns the file error status.
virtual void close()
Calls QFile::flush() and closes the file.
void setFileName(const QString &name)
Sets the name of the file.
◆ rename() [2/2]
|
static |
Renames the file oldName to newName.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Returns true if successful; otherwise returns false.
If a file with the name newName already exists, rename() returns false (i.e., QFile will not overwrite it).
- See also
- rename()
Definition at line 853 of file qfile.cpp.
854 {
855 return QFile(oldName).rename(newName);
856 }
◆ resize() [1/2]
bool QFile::resize | ( | qint64 | 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
- size(), setFileName()
Definition at line 1528 of file qfile.cpp.
Referenced by QFSFileEnginePrivate::longFileName(), and QConfFileSettingsPrivate::syncConfFile().
1529 {
1531 if (!d->ensureFlushed())
1532 return false;
1534 if (isOpen() && d->fileEngine->pos() > sz)
1536 if(d->fileEngine->setSize(sz)) {
1538 d->cachedSize = sz;
1539 return true;
1540 }
1541 d->cachedSize = 0;
1543 return false;
1544 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
bool isOpen() const
Returns true if the device is open; otherwise returns false.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
bool seek(qint64 offset)
For random-access devices, this function sets the current position to pos, returning true on success…
◆ resize() [2/2]
|
static |
Sets fileName to size (in bytes) sz.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
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()
Definition at line 1561 of file qfile.cpp.
1562 {
1563 return QFile(fileName).resize(sz);
1564 }
◆ seek()
|
virtual |
For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred.
For sequential devices, the default behavior is to do nothing and return false.
Seeking beyond the end of a file: If the position is beyond the end of a file, then seek() shall not immediately extend the file. If a write is performed at this position, then the file shall be extended. The content of the file between the previous end of file and the newly written data is UNDEFINED and varies between platforms and file systems.
Reimplemented from QIODevice.
Definition at line 1784 of file qfile.cpp.
Referenced by QTemporaryFile::createLocalFile(), QTransportAuthPrivate::getClientKey(), open(), QFilePrivate::putCharHelper(), QPictureIO::read(), resize(), and QConfFileSettingsPrivate::syncConfFile().
1785 {
1788 qWarning(«QFile::seek: IODevice is not open»);
1789 return false;
1790 }
1791
1792 if (off == d->pos && off == d->devicePos)
1793 return true;
1794
1795 if (!d->ensureFlushed())
1796 return false;
1797
1802 d->setError(err, d->fileEngine->errorString());
1803 return false;
1804 }
1806 return true;
1807 }
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Q_CORE_EXPORT void qWarning(const char *,…)
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
FileError
This enum describes the errors that may be returned by the error() function.
virtual bool seek(qint64 pos)
For random-access devices, this function sets the current position to pos, returning true on success…
◆ setDecodingFunction()
|
static |
Sets the function for decoding 8-bit file names.
- Note
- This class or function is not reentrant.
The default uses the locale-specific 8-bit encoding.
- See also
- setEncodingFunction(), decodeName()
Definition at line 606 of file qfile.cpp.
607 {
608 if (!f)
611 }
static QString locale_decode(const QByteArray &f)
static QFile::DecoderFn decoder
◆ setEncodingFunction()
|
static |
Sets the function for encoding Unicode file names.
- Note
- This class or function is not reentrant.
The default encodes in the locale-specific 8-bit encoding.
- See also
- encodeName(), setDecodingFunction()
Definition at line 572 of file qfile.cpp.
573 {
574 if (!f)
577 }
static QFile::EncoderFn encoder
static QByteArray locale_encode(const QString &f)
◆ setFileName()
void QFile::setFileName | ( | const QString & | name | ) |
Sets the name of the file.
The name can have no path, a relative path, or an 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:
Note that the directory separator «/» works for all operating systems supported by Qt.
- See also
- fileName(), QFileInfo, QDir
Definition at line 494 of file qfile.cpp.
Referenced by QMacPasteboardMimeVCard::convertFromMime(), fontPath(), QImageReaderPrivate::initHandler(), QHostInfo::localDomainName(), QNetworkAccessFileBackend::open(), QFileOpenEvent::openFile(), QIconTheme::QIconTheme(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QPictureIO::read(), rename(), and QPictureIO::write().
495 {
498 qWarning(«QFile::setFileName: File (%s) is already opened»,
501 }
502 if(d->fileEngine) {
503 delete d->fileEngine;
504 d->fileEngine = 0;
505 }
506 d->fileName = name;
507 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Q_CORE_EXPORT void qWarning(const char *,…)
The QFile class provides an interface for reading from and writing to files.
virtual void close()
Calls QFile::flush() and closes the file.
#define qPrintable(string)
◆ setPermissions() [1/2]
bool QFile::setPermissions | ( | Permissions | permissions | ) |
Sets the permissions for the file to the permissions specified.
Returns true if successful, or false if the permissions cannot be modified.
- See also
- permissions(), setFileName()
Definition at line 1605 of file qfile.cpp.
Referenced by copy(), QZipReader::extractAll(), rename(), and QConfFileSettingsPrivate::syncConfFile().
1606 {
1610 return true;
1611 }
1613 return false;
1614 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
bool setPermissions(Permissions permissionSpec)
Sets the permissions for the file to the permissions specified.
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
◆ setPermissions() [2/2]
|
static |
Sets the permissions for fileName file to permissions.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Definition at line 1626 of file qfile.cpp.
1627 {
1629 }
Permissions permissions() const
Returns the complete OR-ed together combination of QFile::Permission for the file.
◆ size()
|
virtual |
Returns the size of the file.
For regular empty files on Unix (e.g. those in /proc
), this function returns 0; the contents of such a file are generated on demand in response to you calling read().
Reimplemented from QIODevice.
Definition at line 1707 of file qfile.cpp.
Referenced by copy(), QNetworkDiskCache::data(), QTranslatorPrivate::do_load(), QNetworkDiskCache::expire(), flush(), open(), qt_parse_pattern(), QDynamicFileResourceRoot::registerSelf(), QCacheItem::size(), and QNetworkDiskCachePrivate::storeItem().
1708 {
1710 if (!d->ensureFlushed())
1711 return 0;
1713 return d->cachedSize;
1714 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
The QFile class provides an interface for reading from and writing to files.
virtual qint64 size() const
Returns the size of the file.
◆ symLinkTarget() [1/2]
|
inline |
Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn’t a symbolic link.
- Since
- 4.2 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
This name may not represent an existing file; it is only a string. QFile::exists() returns true if the symlink points to an existing file.
- See also
- fileName() setFileName()
Definition at line 137 of file qfile.h.
QString readLink() const
Use symLinkTarget() instead.
◆ symLinkTarget() [2/2]
|
inlinestatic |
Returns the absolute path of the file or directory referred to by the symlink (or shortcut on Windows) specified by fileName, or returns an empty string if the fileName does not correspond to a symbolic link.
- Since
- 4.2
This name may not represent an existing file; it is only a string. QFile::exists() returns true if the symlink points to an existing file.
Definition at line 138 of file qfile.h.
138 { return readLink(fileName); }
QString readLink() const
Use symLinkTarget() instead.
◆ unmap()
bool QFile::unmap | ( | uchar * | address | ) |
Unmaps the memory address.
- Since
- 4.4
Returns true if the unmap succeeds; false otherwise.
- See also
- map(), QAbstractFileEngine::supportsExtension()
Definition at line 1485 of file qfile.cpp.
1486 {
1491 bool success = d->fileEngine->unmap(address);
1492 if (!success)
1493 d->setError(d->fileEngine->error(), d->fileEngine->errorString());
1494 return success;
1495 }
1496 d->setError(PermissionsError, tr(«No file engine available or engine does not support UnMapExtension»));
1497 return false;
1498 }
virtual QAbstractFileEngine * fileEngine() const
Returns the QIOEngine for this QFile object.
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
◆ unsetError()
void QFile::unsetError | ( | ) |
Sets the file’s error to QFile::NoError.
- See also
- error()
Definition at line 1996 of file qfile.cpp.
Referenced by close(), copy(), QIODevice::errorString(), link(), map(), open(), readData(), remove(), rename(), resize(), seek(), setPermissions(), unmap(), and writeData().
1997 {
2000 }
The QFile class provides an interface for reading from and writing to files.
◆ writeData()
|
protectedvirtual |
Reimplemented Function
Implements QIODevice.
Definition at line 1923 of file qfile.cpp.
1924 {
1927 d->lastWasWrite = true;
1928 bool buffered = !(d->openMode & Unbuffered);
1929
1930
1933 return -1;
1934 }
1935
1936
1937
1939 qint64 ret = d->fileEngine->write(data, len);
1940 if(ret < 0) {
1944 d->setError(err, d->fileEngine->errorString());
1945 }
1946 return ret;
1947 }
1948
1949
1950 char *writePointer = d->writeBuffer.reserve(len);
1951 if (len == 1)
1952 *writePointer = *data;
1953 else
1954 ::memcpy(writePointer, data, len);
1955 return len;
1956 }
bool flush()
Flushes any buffered data to the file.
static const char * data(const QByteArray &arr)
static const int QFILE_WRITEBUFFER_SIZE
void unsetError()
Sets the file's error to QFile::NoError.
The QFile class provides an interface for reading from and writing to files.
FileError
This enum describes the errors that may be returned by the error() function.
The documentation for this class was generated from the following files:
- /src/corelib/io/qfile.h
- /src/corelib/io/qfile.cpp
The QFile class provides an interface for reading from and writing to files. More…
Member Function Documentation
QFile::QFile ( const QString & name )
Constructs a new file object to represent the file with the given name.
QFile::QFile ( QObject * parent )
Constructs a new file object with the given parent.
QFile::QFile ( const QString & name, QObject * parent )
Constructs a new file object with the given parent to represent the file with the specified name.
QFile::~QFile ()
Destroys the file object, closing it if necessary.
bool QFile::atEnd () const [virtual]
Reimplemented from QIODevice::atEnd().
Returns true if the end of the file has been reached; otherwise returns false.
For regular empty files on Unix (e.g. those in /proc), this function returns true, since the file system reports that the size of such a file is 0. Therefore, you should not depend on atEnd() when reading data from such a file, but rather call read() until no more data can be read.
void QFile::close () [virtual]
Reimplemented from QIODevice::close().
Calls QFile::flush() and closes the file. Errors from flush are ignored.
See also QIODevice::close().
bool QFile::copy ( const QString & newName )
Copies the file currently specified by fileName() to a file called newName. Returns true if successful; otherwise returns false.
Note that if a file with the name newName already exists, copy() returns false (i.e. QFile will not overwrite it).
The source file is closed before it is copied.
See also setFileName().
bool QFile::copy ( const QString & fileName, const QString & newName ) [static]
This is an overloaded function.
Copies the file fileName to newName. Returns true if successful; otherwise returns false.
If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).
See also rename().
QString QFile::decodeName ( const QByteArray & localFileName ) [static]
This does the reverse of QFile::encodeName() using localFileName.
See also setDecodingFunction() and encodeName().
QString QFile::decodeName ( const char * localFileName ) [static]
This is an overloaded 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().
FileError 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.
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 function.
Returns true if the file specified by fileName() exists; otherwise returns false.
See also fileName() and setFileName().
QString QFile::fileName () const
Returns the name set by setFileName() or to the QFile constructors.
See also setFileName() and QFileInfo::fileName().
bool QFile::flush ()
Flushes any buffered data to the file. Returns true if successful; otherwise returns false.
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.
This function is not supported on Windows CE.
On Symbian, this function returns -1 if the file was opened normally, as Symbian OS native file handles do not fit in an int, and are incompatible with C library functions that the handle would be used for. If the file was opened using the overloads that take an open C library file handle / file descriptor, then this function returns that same handle.
See also QSocketNotifier.
bool QFile::isSequential () const [virtual]
Reimplemented from QIODevice::isSequential().
Returns true if the file can only be manipulated sequentially; otherwise returns false.
Most files support random-access, but some special files may not.
See also QIODevice::isSequential().
bool QFile::link ( const QString & linkName )
Creates a link named linkName that points to the file currently specified by fileName(). 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.
This function will not overwrite an already existing entity in the file system; in this case, link() will return false and set error() to return RenameError.
Note: To create a valid link on Windows, linkName must have a .lnk file extension.
Note: Symbian filesystem does not support links.
See also setFileName().
bool QFile::link ( const QString & fileName, const QString & linkName ) [static]
This is an overloaded function.
Creates a link named linkName that points to the file fileName. 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().
uchar * QFile::map ( qint64 offset, qint64 size, MemoryMapFlags flags = NoOptions )
Maps size bytes of the file into memory starting at offset. A file should be open for a map to succeed but the file does not need to stay open after the memory has been mapped. When the QFile is destroyed or a new file is opened with this object, any maps that have not been unmapped will automatically be unmapped.
Any mapping options can be passed through flags.
Returns a pointer to the memory or 0 if there is an error.
Note: On Windows CE 5.0 the file will be closed before mapping occurs.
This function was introduced in Qt 4.4.
See also unmap() and QAbstractFileEngine::supportsExtension().
bool QFile::open ( OpenMode mode ) [virtual]
Reimplemented from QIODevice::open().
Opens the file using OpenMode mode, returning true if successful; otherwise false.
The mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered.
Note: In WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it.
See also QIODevice::OpenMode and setFileName().
bool QFile::open ( FILE * fh, OpenMode mode )
This is an overloaded 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(stderr, QIODevice::WriteOnly); file.write(msg, qstrlen(msg)); file.close(); }
When a QFile is opened using this function, close() does not actually close the file, but only flushes it.
Warning:
- If fh does not refer to a regular file, e.g., it is stdin, stdout, or stderr, you may not be able to seek(). size() returns 0 in those cases. See QIODevice::isSequential() for more information.
- Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
Note: For Windows CE you may not be able to call resize().
Note for the Windows Platform
fh must be opened in binary mode (i.e., the mode string must contain ‘b’, as in «rb» or «wb») when accessing files and other random-access devices. Qt will translate the end-of-line characters if you pass QIODevice::Text to mode. Sequential devices, such as stdin and stdout, are unaffected by this limitation.
You need to enable support for console applications in order to use the stdin, stdout and stderr streams at the console. To do this, add the following declaration to your application’s project file:
CONFIG += console
See also close() and qmake Variable Reference.
bool QFile::open ( FILE * fh, OpenMode mode, FileHandleFlags handleFlags )
This is an overloaded 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(stderr, QIODevice::WriteOnly); file.write(msg, qstrlen(msg)); file.close(); }
When a QFile is opened using this function, behaviour of close() is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified, and this function succeeds, then calling close() closes the adopted handle. Otherwise, close() does not actually close the file, but only flushes it.
Warning:
- If fh does not refer to a regular file, e.g., it is stdin, stdout, or stderr, you may not be able to seek(). size() returns 0 in those cases. See QIODevice::isSequential() for more information.
- Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
Note: For Windows CE you may not be able to call resize().
Note for the Windows Platform
fh must be opened in binary mode (i.e., the mode string must contain ‘b’, as in «rb» or «wb») when accessing files and other random-access devices. Qt will translate the end-of-line characters if you pass QIODevice::Text to mode. Sequential devices, such as stdin and stdout, are unaffected by this limitation.
You need to enable support for console applications in order to use the stdin, stdout and stderr streams at the console. To do this, add the following declaration to your application’s project file:
CONFIG += console
See also close() and qmake Variable Reference.
bool QFile::open ( int fd, OpenMode mode )
This is an overloaded function.
Opens the existing file descriptor 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 not a regular file, e.g, it is 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). In those cases, size() returns 0. See QIODevice::isSequential() for more information.
Warning: For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() returns 0.
Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
See also close().
bool QFile::open ( int fd, OpenMode mode, FileHandleFlags handleFlags )
This is an overloaded function.
Opens the existing file descriptor fd in the given mode. Returns true if successful; otherwise returns false.
When a QFile is opened using this function, behaviour of close() is controlled by the handleFlags argument. If AutoCloseHandle is specified, and this function succeeds, then calling close() closes the adopted handle. Otherwise, close() does not actually close the file, but only flushes it.
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 not a regular file, e.g, it is 0 (stdin), 1 (stdout), or 2 (stderr), you may not be able to seek(). In those cases, size() returns 0. See QIODevice::isSequential() for more information.
Warning: For Windows CE you may not be able to call seek(), setSize(), fileTime(). size() returns 0.
Warning: Since this function opens the file without specifying the file name, you cannot use this QFile with a QFileInfo.
See also close().
bool QFile::open ( const RFile & f, OpenMode mode, FileHandleFlags handleFlags = DontCloseHandle )
This is an overloaded function.
Opens the existing file object f in the given mode. Returns true if successful; otherwise returns false.
When a QFile is opened using this function, behaviour of close() is controlled by the handleFlags argument. If AutoCloseHandle is specified, and this function succeeds, then calling close() closes the adopted handle. Otherwise, close() does not actually close the file, but only flushes it.
Warning: If the file handle is adopted from another process, you may not be able to use this QFile with a QFileInfo.
See also close().
Permissions QFile::permissions () const
Returns the complete OR-ed together combination of QFile::Permission for the file.
See also setPermissions() and setFileName().
Permissions QFile::permissions ( const QString & fileName ) [static]
This is an overloaded function.
Returns the complete OR-ed together combination of QFile::Permission for fileName.
qint64 QFile::pos () const [virtual]
Reimplemented from QIODevice::pos().
qint64 QFile::readData ( char * data, qint64 len ) [virtual protected]
Reimplemented from QIODevice::readData().
qint64 QFile::readLineData ( char * data, qint64 maxlen ) [virtual protected]
Reimplemented from QIODevice::readLineData().
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 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.
If a file with the name newName already exists, rename() returns false (i.e., QFile will not overwrite it).
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 function.
Renames the file oldName to newName. Returns true if successful; otherwise returns false.
If a file with the name newName already exists, rename() returns false (i.e., QFile will not overwrite it).
See also rename().
bool QFile::resize ( qint64 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 size() and setFileName().
bool QFile::resize ( const QString & fileName, qint64 sz ) [static]
This is an overloaded 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().
bool QFile::seek ( qint64 pos ) [virtual]
Reimplemented from QIODevice::seek().
For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. For sequential devices, the default behavior is to do nothing and return false.
Seeking beyond the end of a file: If the position is beyond the end of a file, then seek() shall not immediately extend the file. If a write is performed at this position, then the file shall be extended. The content of the file between the previous end of file and the newly written data is UNDEFINED and varies between platforms and file systems.
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 setEncodingFunction() 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() and setDecodingFunction().
void QFile::setFileName ( const QString & name )
Sets the name of the file. The name can have no path, a relative path, or an 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);
Note that the directory separator «/» works for all operating systems supported by Qt.
See also fileName(), QFileInfo, and QDir.
bool QFile::setPermissions ( Permissions permissions )
Sets the permissions for the file to the permissions specified. Returns true if successful, or false if the permissions cannot be modified.
See also permissions() and setFileName().
bool QFile::setPermissions ( const QString & fileName, Permissions permissions ) [static]
This is an overloaded function.
Sets the permissions for fileName file to permissions.
qint64 QFile::size () const [virtual]
Reimplemented from QIODevice::size().
Returns the size of the file.
For regular empty files on Unix (e.g. those in /proc), this function returns 0; the contents of such a file are generated on demand in response to you calling read().
QString QFile::symLinkTarget ( const QString & fileName ) [static]
Returns the absolute path of the file or directory referred to by the symlink (or shortcut on Windows) specified by fileName, or returns an empty string if the fileName does not correspond to a symbolic link.
This name may not represent an existing file; it is only a string. QFile::exists() returns true if the symlink points to an existing file.
This function was introduced in Qt 4.2.
QString QFile::symLinkTarget () const
This is an overloaded function.
Returns the absolute path of the file or directory 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. QFile::exists() returns true if the symlink points to an existing file.
This function was introduced in Qt 4.2.
See also fileName() and setFileName().
bool QFile::unmap ( uchar * address )
Unmaps the memory address.
Returns true if the unmap succeeds; false otherwise.
This function was introduced in Qt 4.4.
See also map() and QAbstractFileEngine::supportsExtension().
void QFile::unsetError ()
Sets the file’s error to QFile::NoError.
See also error().
qint64 QFile::writeData ( const char * data, qint64 len ) [virtual protected]
Reimplemented from QIODevice::writeData().
Автор | Тема: Как получить код ошибки? (Прочитано 5614 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||