📄 qfile.cpp
字号:
/************************************************************************ Copyright (C) 2000-2005 Trolltech AS. All rights reserved.**** This file is part of the Qtopia Environment.** ** This program is free software; you can redistribute it and/or modify it** under the terms of the GNU General Public License as published by the** Free Software Foundation; either version 2 of the License, or (at your** option) any later version.** ** A copy of the GNU GPL license version 2 is included in this package as ** LICENSE.GPL.**** This program is distributed in the hope that it will be useful, but** WITHOUT ANY WARRANTY; without even the implied warranty of** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ** See the GNU General Public License for more details.**** In addition, as a special exception Trolltech gives permission to link** the code of this program with Qtopia applications copyrighted, developed** and distributed by Trolltech under the terms of the Qtopia Personal Use** License Agreement. You must comply with the GNU General Public License** in all respects for all of the code used other than the applications** licensed under the Qtopia Personal Use License Agreement. If you modify** this file, you may extend this exception to your version of the file,** but you are not obligated to do so. If you do not wish to do so, delete** this exception statement from your version.** ** See http://www.trolltech.com/gpl/ for GPL licensing information.**** Contact info@trolltech.com if any conditions of this licensing are** not clear to you.************************************************************************/#include "qplatformdefs.h"// POSIX Large File Support redefines open -> open64#if defined(open)# undef open#endif// POSIX Large File Support redefines truncate -> truncate64#if defined(truncate)# undef truncate#endif#include "qfile.h"#ifndef NO_ERRNO_H#include <errno.h>#endif// Duplicated from qobject.h, but we cannot include qobject.h here since// it causes qmake to not build on irix g++#define QT_TRANSLATE_NOOP(scope,x) (x)const char* qt_fileerr_unknown = QT_TRANSLATE_NOOP( "QFile", "Unknown error" );const char* qt_fileerr_read = QT_TRANSLATE_NOOP( "QFile", "Could not read from the file" );const char* qt_fileerr_write = QT_TRANSLATE_NOOP( "QFile", "Could not write to the file" );#define QFILEERR_EACCES QT_TRANSLATE_NOOP( "QFile", "Permission denied" )#define QFILEERR_EMFILE QT_TRANSLATE_NOOP( "QFile", "Too many open files" )#define QFILEERR_ENOENT QT_TRANSLATE_NOOP( "QFile", "No such file or directory" )#define QFILEERR_ENOSPC QT_TRANSLATE_NOOP( "QFile", "No space left on device" )class QFilePrivate{public: QString errorString;};extern bool qt_file_access( const QString& fn, int t );/*! \class QFile qfile.h \reentrant \brief The QFile class is an I/O device that operates on files. \ingroup io \mainclass QFile is an I/O device for reading and writing binary and text files. A QFile may be used by itself or more conveniently with a QDataStream or QTextStream. The file name is usually passed in the constructor but can be changed with setName(). You can check for a file's existence with exists() and remove a file with remove(). The file is opened with open(), closed with close() and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can read with readBlock() and readLine() and write with writeBlock(). QFile also supports getch(), ungetch() and putch(). The size of the file is returned by size(). You can get the current file position or move to a new file position using the at() functions. If you've reached the end of the file, atEnd() returns TRUE. The file handle is returned by handle(). Here is a code fragment that uses QTextStream to read a text file line by line. It prints each line with a line number. \code QStringList lines; QFile file( "file.txt" ); if ( file.open( IO_ReadOnly ) ) { QTextStream stream( &file ); QString line; int i = 1; while ( !stream.atEnd() ) { line = stream.readLine(); // line of text excluding '\n' printf( "%3d: %s\n", i++, line.latin1() ); lines += line; } file.close(); } \endcode Writing text is just as easy. The following example shows how to write the data we read into the string list from the previous example: \code QFile file( "file.txt" ); if ( file.open( IO_WriteOnly ) ) { QTextStream stream( &file ); for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) stream << *it << "\n"; file.close(); } \endcode The QFileInfo class holds detailed information about a file, such as access permissions, file dates and file types. The QDir class manages directories and lists of file names. Qt uses Unicode file names. If you want to do your own I/O on Unix systems you may want to use encodeName() (and decodeName()) to convert the file name into the local encoding. \important readAll() \sa QDataStream, QTextStream*//*! \fn Q_LONG QFile::writeBlock( const QByteArray& data ) \overload*//*! Constructs a QFile with no name.*/QFile::QFile(): d(0){ init();}/*! Constructs a QFile with a file name \a name. \sa setName()*/QFile::QFile( const QString &name ) : fn(name), d(0){ init();}/*! Destroys a QFile. Calls close().*/QFile::~QFile(){ close(); delete d;}/*! \internal Initialize internal data.*/void QFile::init(){ delete d; d = new QFilePrivate; setFlags( IO_Direct ); setStatus( IO_Ok ); setErrorString( qt_fileerr_unknown ); fh = 0; fd = 0; length = 0; ioIndex = 0; ext_f = FALSE; // not an external file handle}/*! \fn QString QFile::name() const Returns the name set by setName(). \sa setName(), QFileInfo::fileName()*//*! Sets the name of the file to \a name. The name can have no path, a relative path or an absolute absolute path. Do not call this function if the file has already been opened. If the file name has no path or a relative path, the path used will be whatever the application's current directory path is \e{at the time of the open()} call. Example: \code QFile file; QDir::setCurrent( "/tmp" ); file.setName( "readme.txt" ); QDir::setCurrent( "/home" ); file.open( IO_ReadOnly ); // opens "/home/readme.txt" under Unix \endcode Note that the directory separator "/" works for all operating systems supported by Qt. \sa name(), QFileInfo, QDir*/void QFile::setName( const QString &name ){ if ( isOpen() ) {#if defined(QT_CHECK_STATE) qWarning( "QFile::setName: File is open" );#endif close(); } fn = name;}/*! \overload Returns TRUE if this file exists; otherwise returns FALSE. \sa name()*/bool QFile::exists() const{ return qt_file_access( fn, F_OK );}/*! Returns TRUE if the file given by \a fileName exists; otherwise returns FALSE.*/bool QFile::exists( const QString &fileName ){ return qt_file_access( fileName, F_OK );}/*! Removes the file specified by the file name currently set. Returns TRUE if successful; otherwise returns FALSE. The file is closed before it is removed.*/bool QFile::remove(){ close(); return remove( fn );}#if defined(Q_OS_MAC) || defined(Q_OS_MSDOS) || defined(Q_OS_WIN32) || defined(Q_OS_OS2)# define HAS_TEXT_FILEMODE // has translate/text filemode#endif#if defined(O_NONBLOCK)# define HAS_ASYNC_FILEMODE# define OPEN_ASYNC O_NONBLOCK#elif defined(O_NDELAY)# define HAS_ASYNC_FILEMODE# define OPEN_ASYNC O_NDELAY#endif/*! Flushes the file buffer to the disk. close() also flushes the file buffer.*/void QFile::flush(){ if ( isOpen() && fh ) // can only flush open/buffered fflush( fh ); // file}/*! \reimp \fn QIODevice::Offset QFile::at() const*//*! Returns TRUE if the end of file has been reached; otherwise returns FALSE. If QFile has not been open()'d, then the behavior is undefined. \sa size()*/bool QFile::atEnd() const{ if ( !isOpen() ) {#if defined(QT_CHECK_STATE) qWarning( "QFile::atEnd: File is not open" );#endif return FALSE; } if ( isDirectAccess() && !isTranslated() ) { if ( at() < length ) return FALSE; } return QIODevice::atEnd();}/*! Reads a line of text. Reads bytes from the file into the char* \a p, until end-of-line or \a maxlen bytes have been read, whichever occurs first. Returns the number of bytes read, or -1 if there was an error. Any terminating newline is not stripped. This function is only efficient for buffered files. Avoid readLine() for files that have been opened with the \c IO_Raw flag. \sa readBlock(), QTextStream::readLine()*/Q_LONG QFile::readLine( char *p, Q_ULONG maxlen ){ if ( maxlen == 0 ) // application bug? return 0;#if defined(QT_CHECK_STATE) Q_CHECK_PTR( p ); if ( !isOpen() ) { // file not open qWarning( "QFile::readLine: File not open" ); return -1; } if ( !isReadable() ) { // reading not permitted qWarning( "QFile::readLine: Read operation not permitted" );
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -