1 /****************************************************************************
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtCore module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 #include "qplatformdefs.h"
45 #include "qfsfileengine.h"
46 #include "qtemporaryfile.h"
48 #include "qfileinfo.h"
49 #include "private/qiodevice_p.h"
50 #include "private/qfile_p.h"
51 #if defined(QT_BUILD_CORE_LIB)
52 # include "qcoreapplication.h"
56 #define tr(X) QString::fromLatin1(X)
61 static const int QFILE_WRITEBUFFER_SIZE
= 16384;
63 static QByteArray
locale_encode(const QString
&f
)
66 return f
.toLocal8Bit();
68 // Mac always expects UTF-8... and decomposed...
69 return f
.normalized(QString::NormalizationForm_D
).toUtf8();
73 static QString
locale_decode(const QByteArray
&f
)
76 return QString::fromLocal8Bit(f
);
78 // Mac always gives us UTF-8 and decomposed, we want that composed...
79 return QString::fromUtf8(f
).normalized(QString::NormalizationForm_C
);
83 //************* QFilePrivate
84 QFile::EncoderFn
QFilePrivate::encoder
= locale_encode
;
85 QFile::DecoderFn
QFilePrivate::decoder
= locale_decode
;
87 QFilePrivate::QFilePrivate()
88 : fileEngine(0), lastWasWrite(false),
89 writeBuffer(QFILE_WRITEBUFFER_SIZE
), error(QFile::NoError
)
93 QFilePrivate::~QFilePrivate()
100 QFilePrivate::openExternalFile(int flags
, int fd
)
102 #ifdef QT_NO_FSFILEENGINE
109 QFSFileEngine
*fe
= new QFSFileEngine
;
110 fe
->setFileName(fileName
);
112 return fe
->open(QIODevice::OpenMode(flags
), fd
);
117 QFilePrivate::openExternalFile(int flags
, FILE *fh
)
119 #ifdef QT_NO_FSFILEENGINE
126 QFSFileEngine
*fe
= new QFSFileEngine
;
127 fe
->setFileName(fileName
);
129 return fe
->open(QIODevice::OpenMode(flags
), fh
);
133 inline bool QFilePrivate::ensureFlushed() const
135 // This function ensures that the write buffer has been flushed (const
136 // because certain const functions need to call it.
138 const_cast<QFilePrivate
*>(this)->lastWasWrite
= false;
139 if (!const_cast<QFile
*>(q_func())->flush())
146 QFilePrivate::setError(QFile::FileError err
)
153 QFilePrivate::setError(QFile::FileError err
, const QString
&errStr
)
156 errorString
= errStr
;
160 QFilePrivate::setError(QFile::FileError err
, int errNum
)
163 errorString
= qt_error_string(errNum
);
166 //************* QFile
170 \brief The QFile class provides an interface for reading from and writing to files.
176 QFile is an I/O device for reading and writing text and binary
177 files and \l{The Qt Resource System}{resources}. A QFile may be
178 used by itself or, more conveniently, with a QTextStream or
181 The file name is usually passed in the constructor, but it can be
182 set at any time using setFileName(). QFile expects the file
183 separator to be '/' regardless of operating system. The use of
184 other separators (e.g., '\\') is not supported.
186 You can check for a file's existence using exists(), and remove a
187 file using remove(). (More advanced file system related operations
188 are provided by QFileInfo and QDir.)
190 The file is opened with open(), closed with close(), and flushed
191 with flush(). Data is usually read and written using QDataStream
192 or QTextStream, but you can also call the QIODevice-inherited
193 functions read(), readLine(), readAll(), write(). QFile also
194 inherits getChar(), putChar(), and ungetChar(), which work one
197 The size of the file is returned by size(). You can get the
198 current file position using pos(), or move to a new file position
199 using seek(). If you've reached the end of the file, atEnd()
202 \section1 Reading Files Directly
204 The following example reads a text file line by line:
206 \snippet doc/src/snippets/file/file.cpp 0
208 The QIODevice::Text flag passed to open() tells Qt to convert
209 Windows-style line terminators ("\\r\\n") into C++-style
210 terminators ("\\n"). By default, QFile assumes binary, i.e. it
211 doesn't perform any conversion on the bytes stored in the file.
213 \section1 Using Streams to Read Files
215 The next example uses QTextStream to read a text file
218 \snippet doc/src/snippets/file/file.cpp 1
220 QTextStream takes care of converting the 8-bit data stored on
221 disk into a 16-bit Unicode QString. By default, it assumes that
222 the user system's local 8-bit encoding is used (e.g., ISO 8859-1
223 for most of Europe; see QTextCodec::codecForLocale() for
224 details). This can be changed using setCodec().
226 To write text, we can use operator<<(), which is overloaded to
227 take a QTextStream on the left and various data types (including
228 QString) on the right:
230 \snippet doc/src/snippets/file/file.cpp 2
232 QDataStream is similar, in that you can use operator<<() to write
233 data and operator>>() to read it back. See the class
234 documentation for details.
236 When you use QFile, QFileInfo, and QDir to access the file system
237 with Qt, you can use Unicode file names. On Unix, these file
238 names are converted to an 8-bit encoding. If you want to use
239 standard C++ APIs (\c <cstdio> or \c <iostream>) or
240 platform-specific APIs to access files instead of QFile, you can
241 use the encodeName() and decodeName() functions to convert
242 between Unicode file names and 8-bit file names.
244 On Unix, there are some special system files (e.g. in \c /proc) for which
245 size() will always return 0, yet you may still be able to read more data
246 from such a file; the data is generated in direct response to you calling
247 read(). In this case, however, you cannot use atEnd() to determine if
248 there is more data to read (since atEnd() will return true for a file that
249 claims to have size 0). Instead, you should either call readAll(), or call
250 read() or readLine() repeatedly until no more data can be read. The next
251 example uses QTextStream to read \c /proc/modules line by line:
253 \snippet doc/src/snippets/file/file.cpp 3
257 Unlike other QIODevice implementations, such as QTcpSocket, QFile does not
258 emit the aboutToClose(), bytesWritten(), or readyRead() signals. This
259 implementation detail means that QFile is not suitable for reading and
260 writing certain types of files, such as device files on Unix platforms.
262 \section1 Platform Specific Issues
264 File permissions are handled differently on Linux/Mac OS X and
265 Windows. In a non \l{QIODevice::isWritable()}{writable}
266 directory on Linux, files cannot be created. This is not always
267 the case on Windows, where, for instance, the 'My Documents'
268 directory usually is not writable, but it is still possible to
271 \sa QTextStream, QDataStream, QFileInfo, QDir, {The Qt Resource System}
275 \enum QFile::FileError
277 This enum describes the errors that may be returned by the error()
280 \value NoError No error occurred.
281 \value ReadError An error occurred when reading from the file.
282 \value WriteError An error occurred when writing to the file.
283 \value FatalError A fatal error occurred.
285 \value OpenError The file could not be opened.
286 \value AbortError The operation was aborted.
287 \value TimeOutError A timeout occurred.
288 \value UnspecifiedError An unspecified error occurred.
289 \value RemoveError The file could not be removed.
290 \value RenameError The file could not be renamed.
291 \value PositionError The position in the file could not be changed.
292 \value ResizeError The file could not be resized.
293 \value PermissionsError The file could not be accessed.
294 \value CopyError The file could not be copied.
296 \omitvalue ConnectError
300 \enum QFile::Permission
302 This enum is used by the permission() function to report the
303 permissions and ownership of a file. The values may be OR-ed
304 together to test multiple permissions and ownership values.
306 \value ReadOwner The file is readable by the owner of the file.
307 \value WriteOwner The file is writable by the owner of the file.
308 \value ExeOwner The file is executable by the owner of the file.
309 \value ReadUser The file is readable by the user.
310 \value WriteUser The file is writable by the user.
311 \value ExeUser The file is executable by the user.
312 \value ReadGroup The file is readable by the group.
313 \value WriteGroup The file is writable by the group.
314 \value ExeGroup The file is executable by the group.
315 \value ReadOther The file is readable by anyone.
316 \value WriteOther The file is writable by anyone.
317 \value ExeOther The file is executable by anyone.
319 \warning Because of differences in the platforms supported by Qt,
320 the semantics of ReadUser, WriteUser and ExeUser are
321 platform-dependent: On Unix, the rights of the owner of the file
322 are returned and on Windows the rights of the current user are
323 returned. This behavior might change in a future Qt version.
325 Note that Qt does not by default check for permissions on NTFS
326 file systems, as this may decrease the performance of file
327 handling considerably. It is possible to force permission checking
328 on NTFS by including the following code in your source:
330 \snippet doc/src/snippets/ntfsp.cpp 0
332 Permission checking is then turned on and off by incrementing and
333 decrementing \c qt_ntfs_permission_lookup by 1.
335 \snippet doc/src/snippets/ntfsp.cpp 1
340 \typedef QFile::PermissionSpec
342 Use QFile::Permission instead.
348 : QIODevice(*new QFilePrivate
)
351 QFile::QFile(const QString
&name
)
352 : QIODevice(*new QFilePrivate
)
354 d_func()->fileName
= name
;
356 QFile::QFile(QFilePrivate
&dd
)
365 : QIODevice(*new QFilePrivate
, 0)
369 Constructs a new file object with the given \a parent.
371 QFile::QFile(QObject
*parent
)
372 : QIODevice(*new QFilePrivate
, parent
)
376 Constructs a new file object to represent the file with the given \a name.
378 QFile::QFile(const QString
&name
)
379 : QIODevice(*new QFilePrivate
, 0)
385 Constructs a new file object with the given \a parent to represent the
386 file with the specified \a name.
388 QFile::QFile(const QString
&name
, QObject
*parent
)
389 : QIODevice(*new QFilePrivate
, parent
)
397 QFile::QFile(QFilePrivate
&dd
, QObject
*parent
)
398 : QIODevice(dd
, parent
)
404 Destroys the file object, closing it if necessary.
412 Returns the name set by setFileName() or to the QFile
415 \sa setFileName(), QFileInfo::fileName()
417 QString
QFile::fileName() const
419 return fileEngine()->fileName(QAbstractFileEngine::DefaultName
);
423 Sets the \a name of the file. The name can have no path, a
424 relative path, or an absolute path.
426 Do not call this function if the file has already been opened.
428 If the file name has no path or a relative path, the path used
429 will be the application's current directory path
430 \e{at the time of the open()} call.
433 \snippet doc/src/snippets/code/src_corelib_io_qfile.cpp 0
435 Note that the directory separator "/" works for all operating
436 systems supported by Qt.
438 \sa fileName(), QFileInfo, QDir
441 QFile::setFileName(const QString
&name
)
445 qWarning("QFile::setFileName: File (%s) is already opened",
446 qPrintable(fileName()));
449 if(d
->fileEngine
) { //get a new file engine later
450 delete d
->fileEngine
;
457 \fn QString QFile::decodeName(const char *localFileName)
461 Returns the Unicode version of the given \a localFileName. See
462 encodeName() for details.
466 By default, this function converts \a fileName to the local 8-bit
467 encoding determined by the user's locale. This is sufficient for
468 file names that the user chooses. File names hard-coded into the
469 application should only use 7-bit ASCII filename characters.
471 \sa decodeName() setEncodingFunction()
475 QFile::encodeName(const QString
&fileName
)
477 return (*QFilePrivate::encoder
)(fileName
);
481 \typedef QFile::EncoderFn
483 This is a typedef for a pointer to a function with the following
486 \snippet doc/src/snippets/code/src_corelib_io_qfile.cpp 1
488 \sa setEncodingFunction(), encodeName()
492 This does the reverse of QFile::encodeName() using \a localFileName.
494 \sa setDecodingFunction(), encodeName()
498 QFile::decodeName(const QByteArray
&localFileName
)
500 return (*QFilePrivate::decoder
)(localFileName
);
504 \fn void QFile::setEncodingFunction(EncoderFn function)
508 Sets the \a function for encoding Unicode file names. The
509 default encodes in the locale-specific 8-bit encoding.
511 \sa encodeName(), setDecodingFunction()
515 QFile::setEncodingFunction(EncoderFn f
)
519 QFilePrivate::encoder
= f
;
523 \typedef QFile::DecoderFn
525 This is a typedef for a pointer to a function with the following
528 \snippet doc/src/snippets/code/src_corelib_io_qfile.cpp 2
530 \sa setDecodingFunction()
534 \fn void QFile::setDecodingFunction(DecoderFn function)
538 Sets the \a function for decoding 8-bit file names. The
539 default uses the locale-specific 8-bit encoding.
541 \sa setEncodingFunction(), decodeName()
545 QFile::setDecodingFunction(DecoderFn f
)
549 QFilePrivate::decoder
= f
;
555 Returns true if the file specified by fileName() exists; otherwise
558 \sa fileName(), setFileName()
562 QFile::exists() const
564 // 0x1000000 = QAbstractFileEngine::Refresh, forcing an update
565 return (fileEngine()->fileFlags(QAbstractFileEngine::FlagsMask
566 | QAbstractFileEngine::FileFlag(0x1000000)) & QAbstractFileEngine::ExistsFlag
);
570 Returns true if the file specified by \a fileName exists; otherwise
575 QFile::exists(const QString
&fileName
)
577 return QFileInfo(fileName
).exists();
581 \fn QString QFile::symLinkTarget() const
585 Returns the absolute path of the file or directory a symlink (or shortcut
586 on Windows) points to, or a an empty string if the object isn't a symbolic
589 This name may not represent an existing file; it is only a string.
590 QFile::exists() returns true if the symlink points to an existing file.
592 \sa fileName() setFileName()
598 Use symLinkTarget() instead.
601 QFile::readLink() const
603 return fileEngine()->fileName(QAbstractFileEngine::LinkName
);
607 \fn static QString QFile::symLinkTarget(const QString &fileName)
610 Returns the absolute path of the file or directory referred to by the
611 symlink (or shortcut on Windows) specified by \a fileName, or returns an
612 empty string if the \a fileName does not correspond to a symbolic link.
614 This name may not represent an existing file; it is only a string.
615 QFile::exists() returns true if the symlink points to an existing file.
621 Use symLinkTarget() instead.
624 QFile::readLink(const QString
&fileName
)
626 return QFileInfo(fileName
).readLink();
630 Removes the file specified by fileName(). Returns true if successful;
631 otherwise returns false.
633 The file is closed before it is removed.
642 if (d
->fileName
.isEmpty()) {
643 qWarning("QFile::remove: Empty or null file name");
647 if(error() == QFile::NoError
) {
648 if(fileEngine()->remove()) {
652 d
->setError(QFile::RemoveError
, fileEngine()->errorString());
660 Removes the file specified by the \a fileName given.
662 Returns true if successful; otherwise returns false.
668 QFile::remove(const QString
&fileName
)
670 return QFile(fileName
).remove();
674 Renames the file currently specified by fileName() to \a newName.
675 Returns true if successful; otherwise returns false.
677 If a file with the name \a newName already exists, rename() returns false
678 (i.e., QFile will not overwrite it).
680 The file is closed before it is renamed.
686 QFile::rename(const QString
&newName
)
689 if (d
->fileName
.isEmpty()) {
690 qWarning("QFile::rename: Empty or null file name");
693 if (QFile(newName
).exists()) {
694 // ### Race condition. If a file is moved in after this, it /will/ be
695 // overwritten. On Unix, the proper solution is to use hardlinks:
696 // return ::link(old, new) && ::remove(old);
697 d
->setError(QFile::RenameError
, tr("Destination file exists"));
702 if(error() == QFile::NoError
) {
703 if (fileEngine()->rename(newName
)) {
705 // engine was able to handle the new name so we just reset it
706 fileEngine()->setFileName(newName
);
707 d
->fileName
= newName
;
711 if (isSequential()) {
712 d
->setError(QFile::RenameError
, tr("Will not rename sequential file using block copy"));
717 if (open(QIODevice::ReadOnly
)) {
718 if (out
.open(QIODevice::WriteOnly
| QIODevice::Truncate
)) {
722 while ((bytes
= read(block
, sizeof(block
))) > 0) {
723 if (bytes
!= out
.write(block
, bytes
)) {
724 d
->setError(QFile::RenameError
, out
.errorString());
730 d
->setError(QFile::RenameError
, errorString());
735 d
->setError(QFile::RenameError
, tr("Cannot remove source file"));
742 fileEngine()->setFileName(newName
);
743 setPermissions(permissions());
745 setFileName(newName
);
752 d
->setError(QFile::RenameError
, out
.isOpen() ? errorString() : out
.errorString());
760 Renames the file \a oldName to \a newName. Returns true if
761 successful; otherwise returns false.
763 If a file with the name \a newName already exists, rename() returns false
764 (i.e., QFile will not overwrite it).
770 QFile::rename(const QString
&oldName
, const QString
&newName
)
772 return QFile(oldName
).rename(newName
);
777 Creates a link named \a linkName that points to the file currently specified by
778 fileName(). What a link is depends on the underlying filesystem (be it a
779 shortcut on Windows or a symbolic link on Unix). Returns true if successful;
780 otherwise returns false.
782 This function will not overwrite an already existing entity in the file system;
783 in this case, \c link() will return false and set \l{QFile::}{error()} to
784 return \l{QFile::}{RenameError}.
786 \note To create a valid link on Windows, \a linkName must have a \c{.lnk} file extension.
788 \note On Symbian, no link is created and false is returned if fileName()
789 currently specifies a directory.
795 QFile::link(const QString
&linkName
)
798 if (d
->fileName
.isEmpty()) {
799 qWarning("QFile::link: Empty or null file name");
802 QFileInfo
fi(linkName
);
803 if(fileEngine()->link(fi
.absoluteFilePath())) {
807 d
->setError(QFile::RenameError
, fileEngine()->errorString());
814 Creates a link named \a linkName that points to the file \a fileName. What a link is
815 depends on the underlying filesystem (be it a shortcut on Windows
816 or a symbolic link on Unix). Returns true if successful; otherwise
823 QFile::link(const QString
&fileName
, const QString
&linkName
)
825 return QFile(fileName
).link(linkName
);
829 Copies the file currently specified by fileName() to a file called
830 \a newName. Returns true if successful; otherwise returns false.
832 Note that if a file with the name \a newName already exists,
833 copy() returns false (i.e. QFile will not overwrite it).
835 The source file is closed before it is copied.
841 QFile::copy(const QString
&newName
)
844 if (d
->fileName
.isEmpty()) {
845 qWarning("QFile::copy: Empty or null file name");
848 if (QFile(newName
).exists()) {
849 // ### Race condition. If a file is moved in after this, it /will/ be
850 // overwritten. On Unix, the proper solution is to use hardlinks:
851 // return ::link(old, new) && ::remove(old); See also rename().
852 d
->setError(QFile::CopyError
, tr("Destination file exists"));
857 if(error() == QFile::NoError
) {
858 if(fileEngine()->copy(newName
)) {
863 if(!open(QFile::ReadOnly
)) {
865 d
->setError(QFile::CopyError
, tr("Cannot open %1 for input").arg(d
->fileName
));
867 QString fileTemplate
= QLatin1String("%1/qt_temp.XXXXXX");
868 #ifdef QT_NO_TEMPORARYFILE
869 QFile
out(fileTemplate
.arg(QFileInfo(newName
).path()));
870 if (!out
.open(QIODevice::ReadWrite
))
873 QTemporaryFile
out(fileTemplate
.arg(QFileInfo(newName
).path()));
875 out
.setFileTemplate(fileTemplate
.arg(QDir::tempPath()));
882 d
->setError(QFile::CopyError
, tr("Cannot open for output"));
885 qint64 totalRead
= 0;
887 qint64 in
= read(block
, sizeof(block
));
891 if(in
!= out
.write(block
, in
)) {
892 d
->setError(QFile::CopyError
, tr("Failure to write block"));
898 if (totalRead
!= size()) {
899 // Unable to read from the source. The error string is
900 // already set from read().
903 if (!error
&& !out
.rename(newName
)) {
905 d
->setError(QFile::CopyError
, tr("Cannot create %1 for output").arg(newName
));
907 #ifdef QT_NO_TEMPORARYFILE
912 out
.setAutoRemove(false);
918 QFile::setPermissions(newName
, permissions());
930 Copies the file \a fileName to \a newName. Returns true if successful;
931 otherwise returns false.
933 If a file with the name \a newName already exists, copy() returns false
934 (i.e., QFile will not overwrite it).
940 QFile::copy(const QString
&fileName
, const QString
&newName
)
942 return QFile(fileName
).copy(newName
);
946 Returns true if the file can only be manipulated sequentially;
947 otherwise returns false.
949 Most files support random-access, but some special files may not.
951 \sa QIODevice::isSequential()
953 bool QFile::isSequential() const
956 return d
->fileEngine
&& d
->fileEngine
->isSequential();
960 Opens the file using OpenMode \a mode, returning true if successful;
963 The \a mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or
964 QIODevice::ReadWrite. It may also have additional flags, such as
965 QIODevice::Text and QIODevice::Unbuffered.
967 \note In \l{QIODevice::}{WriteOnly} or \l{QIODevice::}{ReadWrite}
968 mode, if the relevant file does not already exist, this function
969 will try to create a new file before opening it.
971 \sa QIODevice::OpenMode, setFileName()
973 bool QFile::open(OpenMode mode
)
977 qWarning("QFile::open: File (%s) already open", qPrintable(fileName()));
984 if ((mode
& (ReadOnly
| WriteOnly
)) == 0) {
985 qWarning("QIODevice::open: File access not specified");
989 // QIODevice provides the buffering, so there's no need to request it from the file engine.
990 if (fileEngine()->open(mode
| QIODevice::Unbuffered
)) {
991 QIODevice::open(mode
);
996 QFile::FileError err
= fileEngine()->error();
997 if(err
== QFile::UnspecifiedError
)
998 err
= QFile::OpenError
;
999 d
->setError(err
, fileEngine()->errorString());
1003 /*! \fn QFile::open(OpenMode, FILE*)
1005 Use open(FILE *, OpenMode) instead.
1011 Opens the existing file handle \a fh in the given \a mode.
1012 Returns true if successful; otherwise returns false.
1015 \snippet doc/src/snippets/code/src_corelib_io_qfile.cpp 3
1017 When a QFile is opened using this function, close() does not actually
1018 close the file, but only flushes it.
1022 \o If \a fh does not refer to a regular file, e.g., it is \c stdin,
1023 \c stdout, or \c stderr, you may not be able to seek(). size()
1024 returns \c 0 in those cases. See QIODevice::isSequential() for
1026 \o Since this function opens the file without specifying the file name,
1027 you cannot use this QFile with a QFileInfo.
1030 \note For Windows CE you may not be able to call resize().
1032 \sa close(), {qmake Variable Reference#CONFIG}{qmake Variable Reference}
1034 \bold{Note for the Windows Platform}
1036 \a fh must be opened in binary mode (i.e., the mode string must contain
1037 'b', as in "rb" or "wb") when accessing files and other random-access
1038 devices. Qt will translate the end-of-line characters if you pass
1039 QIODevice::Text to \a mode. Sequential devices, such as stdin and stdout,
1040 are unaffected by this limitation.
1042 You need to enable support for console applications in order to use the
1043 stdin, stdout and stderr streams at the console. To do this, add the
1044 following declaration to your application's project file:
1046 \snippet doc/src/snippets/code/src_corelib_io_qfile.cpp 4
1048 bool QFile::open(FILE *fh
, OpenMode mode
)
1052 qWarning("QFile::open: File (%s) already open", qPrintable(fileName()));
1058 if ((mode
& (ReadOnly
| WriteOnly
)) == 0) {
1059 qWarning("QFile::open: File access not specified");
1062 if(d
->openExternalFile(mode
, fh
)) {
1063 QIODevice::open(mode
);
1064 if (mode
& Append
) {
1067 qint64 pos
= (qint64
)QT_FTELL(fh
);
1076 /*! \fn QFile::open(OpenMode, int)
1078 Use open(int, OpenMode) instead.
1084 Opens the existing file descriptor \a fd in the given \a mode.
1085 Returns true if successful; otherwise returns false.
1087 When a QFile is opened using this function, close() does not
1088 actually close the file.
1090 The QFile that is opened using this function is automatically set
1091 to be in raw mode; this means that the file input/output functions
1092 are slow. If you run into performance issues, you should try to
1093 use one of the other open functions.
1095 \warning If \a fd is not a regular file, e.g, it is 0 (\c stdin),
1096 1 (\c stdout), or 2 (\c stderr), you may not be able to seek(). In
1097 those cases, size() returns \c 0. See QIODevice::isSequential()
1098 for more information.
1100 \warning For Windows CE you may not be able to call seek(), setSize(),
1101 fileTime(). size() returns \c 0.
1103 \warning Since this function opens the file without specifying the file name,
1104 you cannot use this QFile with a QFileInfo.
1108 bool QFile::open(int fd
, OpenMode mode
)
1112 qWarning("QFile::open: File (%s) already open", qPrintable(fileName()));
1118 if ((mode
& (ReadOnly
| WriteOnly
)) == 0) {
1119 qWarning("QFile::open: File access not specified");
1122 if(d
->openExternalFile(mode
, fd
)) {
1123 QIODevice::open(mode
);
1124 if (mode
& Append
) {
1127 qint64 pos
= (qint64
)QT_LSEEK(fd
, QT_OFF_T(0), SEEK_CUR
);
1137 Returns the file handle of the file.
1139 This is a small positive integer, suitable for use with C library
1140 functions such as fdopen() and fcntl(). On systems that use file
1141 descriptors for sockets (i.e. Unix systems, but not Windows) the handle
1142 can be used with QSocketNotifier as well.
1144 If the file is not open, or there is an error, handle() returns -1.
1146 This function is not supported on Windows CE.
1152 QFile::handle() const
1157 if (QAbstractFileEngine
*engine
= fileEngine())
1158 return engine
->handle();
1163 \enum QFile::MemoryMapFlags
1166 This enum describes special options that may be used by the map()
1169 \value NoOptions No options.
1174 Maps \a size bytes of the file into memory starting at \a offset. A file
1175 should be open for a map to succeed but the file does not need to stay
1176 open after the memory has been mapped. When the QFile is destroyed
1177 or a new file is opened with this object, any maps that have not been
1178 unmapped will automatically be unmapped.
1180 Any mapping options can be passed through \a flags.
1182 Returns a pointer to the memory or 0 if there is an error.
1184 \note On Windows CE 5.0 the file will be closed before mapping occurs.
1186 \sa unmap(), QAbstractFileEngine::supportsExtension()
1188 uchar
*QFile::map(qint64 offset
, qint64 size
, MemoryMapFlags flags
)
1191 QAbstractFileEngine
*engine
= fileEngine();
1193 && engine
->supportsExtension(QAbstractFileEngine::MapExtension
)) {
1195 uchar
*address
= engine
->map(offset
, size
, flags
);
1197 d
->setError(engine
->error(), engine
->errorString());
1205 Unmaps the memory \a address.
1207 Returns true if the unmap succeeds; false otherwise.
1209 \sa map(), QAbstractFileEngine::supportsExtension()
1211 bool QFile::unmap(uchar
*address
)
1214 QAbstractFileEngine
*engine
= fileEngine();
1216 && engine
->supportsExtension(QAbstractFileEngine::UnMapExtension
)) {
1218 bool success
= engine
->unmap(address
);
1220 d
->setError(engine
->error(), engine
->errorString());
1227 \fn QString QFile::name() const
1229 Use fileName() instead.
1233 \fn void QFile::setName(const QString &name)
1235 Use setFileName() instead.
1239 Sets the file size (in bytes) \a sz. Returns true if the file if the
1240 resize succeeds; false otherwise. If \a sz is larger than the file
1241 currently is the new bytes will be set to 0, if \a sz is smaller the
1242 file is simply truncated.
1244 \sa size(), setFileName()
1248 QFile::resize(qint64 sz
)
1251 if (!d
->ensureFlushed())
1253 if (isOpen() && fileEngine()->pos() > sz
)
1255 if(fileEngine()->setSize(sz
)) {
1259 d
->setError(QFile::ResizeError
, fileEngine()->errorString());
1266 Sets \a fileName to size (in bytes) \a sz. Returns true if the file if
1267 the resize succeeds; false otherwise. If \a sz is larger than \a
1268 fileName currently is the new bytes will be set to 0, if \a sz is
1269 smaller the file is simply truncated.
1275 QFile::resize(const QString
&fileName
, qint64 sz
)
1277 return QFile(fileName
).resize(sz
);
1281 Returns the complete OR-ed together combination of
1282 QFile::Permission for the file.
1284 \sa setPermissions(), setFileName()
1288 QFile::permissions() const
1290 QAbstractFileEngine::FileFlags perms
= fileEngine()->fileFlags(QAbstractFileEngine::PermsMask
) & QAbstractFileEngine::PermsMask
;
1291 return QFile::Permissions((int)perms
); //ewww
1297 Returns the complete OR-ed together combination of
1298 QFile::Permission for \a fileName.
1302 QFile::permissions(const QString
&fileName
)
1304 return QFile(fileName
).permissions();
1308 Sets the permissions for the file to the \a permissions specified.
1309 Returns true if successful, or false if the permissions cannot be
1312 \sa permissions(), setFileName()
1316 QFile::setPermissions(Permissions permissions
)
1319 if(fileEngine()->setPermissions(permissions
)) {
1323 d
->setError(QFile::PermissionsError
, fileEngine()->errorString());
1330 Sets the permissions for \a fileName file to \a permissions.
1334 QFile::setPermissions(const QString
&fileName
, Permissions permissions
)
1336 return QFile(fileName
).setPermissions(permissions
);
1339 static inline qint64
_qfile_writeData(QAbstractFileEngine
*engine
, QRingBuffer
*buffer
)
1341 qint64 ret
= engine
->write(buffer
->readPointer(), buffer
->nextDataBlockSize());
1348 Flushes any buffered data to the file. Returns true if successful;
1349 otherwise returns false.
1356 if (!d
->writeBuffer
.isEmpty()) {
1357 qint64 size
= d
->writeBuffer
.size();
1358 if (_qfile_writeData(d
->fileEngine
? d
->fileEngine
: fileEngine(),
1359 &d
->writeBuffer
) != size
) {
1360 QFile::FileError err
= fileEngine()->error();
1361 if(err
== QFile::UnspecifiedError
)
1362 err
= QFile::WriteError
;
1363 d
->setError(err
, fileEngine()->errorString());
1368 if (!fileEngine()->flush()) {
1369 QFile::FileError err
= fileEngine()->error();
1370 if(err
== QFile::UnspecifiedError
)
1371 err
= QFile::WriteError
;
1372 d
->setError(err
, fileEngine()->errorString());
1379 Calls QFile::flush() and closes the file. Errors from flush are ignored.
1381 \sa QIODevice::close()
1389 bool flushed
= flush();
1392 // reset write buffer
1393 d
->lastWasWrite
= false;
1394 d
->writeBuffer
.clear();
1396 // keep earlier error from flush
1397 if (fileEngine()->close() && flushed
)
1400 d
->setError(fileEngine()->error(), fileEngine()->errorString());
1404 Returns the size of the file.
1406 For regular empty files on Unix (e.g. those in \c /proc), this function
1407 returns 0; the contents of such a file are generated on demand in response
1408 to you calling read().
1411 qint64
QFile::size() const
1414 if (!d
->ensureFlushed())
1416 return fileEngine()->size();
1423 qint64
QFile::pos() const
1425 return QIODevice::pos();
1429 Returns true if the end of the file has been reached; otherwise returns
1432 For regular empty files on Unix (e.g. those in \c /proc), this function
1433 returns true, since the file system reports that the size of such a file is
1434 0. Therefore, you should not depend on atEnd() when reading data from such a
1435 file, but rather call read() until no more data can be read.
1438 bool QFile::atEnd() const
1445 if (!d
->ensureFlushed())
1448 // If there's buffered data left, we're not at the end.
1449 if (!d
->buffer
.isEmpty())
1452 // If the file engine knows best, say what it says.
1453 if (fileEngine()->supportsExtension(QAbstractFileEngine::AtEndExtension
)) {
1454 // Check if the file engine supports AtEndExtension, and if it does,
1455 // check if the file engine claims to be at the end.
1456 return fileEngine()->atEnd();
1459 // Fall back to checking how much is available (will stat files).
1460 return bytesAvailable() == 0;
1467 bool QFile::seek(qint64 off
)
1471 qWarning("QFile::seek: IODevice is not open");
1475 if (!d
->ensureFlushed())
1478 if (!fileEngine()->seek(off
) || !QIODevice::seek(off
)) {
1479 QFile::FileError err
= fileEngine()->error();
1480 if(err
== QFile::UnspecifiedError
)
1481 err
= QFile::PositionError
;
1482 d
->setError(err
, fileEngine()->errorString());
1492 qint64
QFile::readLineData(char *data
, qint64 maxlen
)
1495 if (!d
->ensureFlushed())
1498 if (fileEngine()->supportsExtension(QAbstractFileEngine::FastReadLineExtension
))
1499 return fileEngine()->readLine(data
, maxlen
);
1501 // Fall back to QIODevice's readLine implementation if the engine
1502 // cannot do it faster.
1503 return QIODevice::readLineData(data
, maxlen
);
1510 qint64
QFile::readData(char *data
, qint64 len
)
1514 if (!d
->ensureFlushed())
1518 qint64 read
= fileEngine()->read(data
, len
);
1523 QFile::FileError err
= fileEngine()->error();
1524 if(err
== QFile::UnspecifiedError
)
1525 err
= QFile::ReadError
;
1526 d
->setError(err
, fileEngine()->errorString());
1534 bool QFilePrivate::putCharHelper(char c
)
1536 #ifdef QT_NO_QOBJECT
1537 return QIODevicePrivate::putCharHelper(c
);
1540 // Cutoff for code that doesn't only touch the buffer.
1541 int writeBufferSize
= writeBuffer
.size();
1542 if ((openMode
& QIODevice::Unbuffered
) || writeBufferSize
+ 1 >= QFILE_WRITEBUFFER_SIZE
1544 || ((openMode
& QIODevice::Text
) && c
== '\n' && writeBufferSize
+ 2 >= QFILE_WRITEBUFFER_SIZE
)
1547 return QIODevicePrivate::putCharHelper(c
);
1550 if (!(openMode
& QIODevice::WriteOnly
)) {
1551 if (openMode
== QIODevice::NotOpen
)
1552 qWarning("QIODevice::putChar: Closed device");
1554 qWarning("QIODevice::putChar: ReadOnly device");
1558 // Make sure the device is positioned correctly.
1559 const bool sequential
= isSequential();
1560 if (pos
!= devicePos
&& !sequential
&& !q_func()->seek(pos
))
1563 lastWasWrite
= true;
1567 if ((openMode
& QIODevice::Text
) && c
== '\n') {
1569 *writeBuffer
.reserve(1) = '\r';
1574 *writeBuffer
.reserve(1) = c
;
1579 if (!buffer
.isEmpty())
1592 QFile::writeData(const char *data
, qint64 len
)
1596 d
->lastWasWrite
= true;
1597 bool buffered
= !(d
->openMode
& Unbuffered
);
1599 // Flush buffered data if this read will overflow.
1600 if (buffered
&& (d
->writeBuffer
.size() + len
) > QFILE_WRITEBUFFER_SIZE
) {
1605 // Write directly to the engine if the block size is larger than
1606 // the write buffer size.
1607 if (!buffered
|| len
> QFILE_WRITEBUFFER_SIZE
) {
1608 QAbstractFileEngine
*fe
= d
->fileEngine
? d
->fileEngine
: fileEngine();
1609 qint64 ret
= fe
->write(data
, len
);
1611 QFile::FileError err
= fileEngine()->error();
1612 if(err
== QFile::UnspecifiedError
)
1613 err
= QFile::WriteError
;
1614 d
->setError(err
, fileEngine()->errorString());
1619 // Write to the buffer.
1620 char *writePointer
= d
->writeBuffer
.reserve(len
);
1622 *writePointer
= *data
;
1624 ::memcpy(writePointer
, data
, len
);
1630 Returns the QIOEngine for this QFile object.
1632 QAbstractFileEngine
*QFile::fileEngine() const
1636 d
->fileEngine
= QAbstractFileEngine::create(d
->fileName
);
1637 return d
->fileEngine
;
1641 Returns the file error status.
1643 The I/O device status returns an error code. For example, if open()
1644 returns false, or a read/write operation returns -1, this function can
1645 be called to find out the reason why the operation failed.
1651 QFile::error() const
1658 Sets the file's error to QFile::NoError.
1666 d
->setError(QFile::NoError
);