1 /****************************************************************************
4 ** Implementation of QFile class
8 ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
10 ** This file is part of the tools module of the Qt GUI Toolkit.
12 ** This file may be distributed under the terms of the Q Public License
13 ** as defined by Trolltech AS of Norway and appearing in the file
14 ** LICENSE.QPL included in the packaging of this file.
16 ** This file may be distributed and/or modified under the terms of the
17 ** GNU General Public License version 2 as published by the Free Software
18 ** Foundation and appearing in the file LICENSE.GPL included in the
19 ** packaging of this file.
21 ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22 ** licenses may use this file in accordance with the Qt Commercial License
23 ** Agreement provided with the Software.
25 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
28 ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29 ** information about Qt Commercial License Agreements.
30 ** See http://www.trolltech.com/qpl/ for QPL licensing information.
31 ** See http://www.trolltech.com/gpl/ for GPL licensing information.
33 ** Contact info@trolltech.com if any conditions of this licensing are
36 **********************************************************************/
39 #if defined(_OS_WIN32_)
48 #include "qfiledefs_p.h"
50 extern bool qt_file_access( const QString& fn, int t );
55 \brief The QFile class is an I/O device that operates on files.
59 QFile is an I/O device for reading and writing binary and text files. A
60 QFile may be used by itself (readBlock and writeBlock) or by more
61 conveniently using QDataStream or QTextStream.
63 Here is a code fragment that uses QTextStream to read a text
64 file line by line. It prints each line with a line number.
67 if ( f.open(IO_ReadOnly) ) { // file opened successfully
68 QTextStream t( &f ); // use a text stream
71 while ( !t.eof() ) { // until end of file...
72 s = t.readLine(); // line of text excluding '\n'
73 printf( "%3d: %s\n", n++, (const char *)s );
79 The QFileInfo class holds detailed information about a file, such as
80 access permissions, file dates and file types.
82 The QDir class manages directories and lists of file names.
84 \sa QDataStream, QTextStream
89 Constructs a QFile with no name.
98 Constructs a QFile with a file name \e name.
102 QFile::QFile( const QString &name )
110 Destructs a QFile. Calls close().
121 Initialize internal data.
126 setFlags( IO_Direct );
132 ext_f = FALSE; // not an external file handle
137 \fn QString QFile::name() const
138 Returns the name set by setName().
139 \sa setName(), QFileInfo::fileName()
143 Sets the name of the file. The name can include an absolute directory
144 path or it can be a name or a path relative to the current directory.
146 Do not call this function if the file has already been opened.
148 Note that if the name is relative QFile does not associate it with the
149 current directory. If you change directory before calling open(), open
150 uses the new current directory.
155 QDir::setCurrent( "/tmp" );
156 f.setName( "readme.txt" );
157 QDir::setCurrent( "/home" );
158 f.open( IO_ReadOnly ); // opens "/home/readme.txt" under UNIX
161 Also note that the directory separator '/' works for all operating
162 systems supported by Qt.
164 \sa name(), QFileInfo, QDir
167 void QFile::setName( const QString &name )
170 #if defined(CHECK_STATE)
171 qWarning( "QFile::setName: File is open" );
179 Returns TRUE if this file exists, otherwise FALSE.
183 bool QFile::exists() const
185 return qt_file_access( fn, F_OK );
189 Returns TRUE if the file given by \e fileName exists, otherwise FALSE.
192 bool QFile::exists( const QString &fileName )
194 return qt_file_access( fileName, F_OK );
199 Removes the file specified by the file name currently set.
200 Returns TRUE if successful, otherwise FALSE.
202 The file is closed before it is removed.
211 #if defined(_OS_MAC_) || defined(_OS_MSDOS_) || defined(_OS_WIN32_) || defined(_OS_OS2_) || defined(_OS_CYGWIN_)
212 # define HAS_TEXT_FILEMODE // has translate/text filemode
214 #if defined(O_NONBLOCK)
215 # define HAS_ASYNC_FILEMODE
216 # define OPEN_ASYNC O_NONBLOCK
217 #elif defined(O_NDELAY)
218 # define HAS_ASYNC_FILEMODE
219 # define OPEN_ASYNC O_NDELAY
223 Flushes the file buffer to the disk.
225 close() also flushes the file buffer.
230 if ( isOpen() && fh ) // can only flush open/buffered
231 fflush( fh ); // file
235 Returns TRUE if the end of file has been reached, otherwise FALSE.
239 bool QFile::atEnd() const
242 #if defined(CHECK_STATE)
243 qWarning( "QFile::atEnd: File is not open" );
247 if ( isDirectAccess() && !isTranslated() ) {
251 return QIODevice::atEnd();
255 Reads a line of text.
257 Reads bytes from the file until end-of-line is reached, or up to \a
258 maxlen bytes, and returns the number of bytes read, or -1 in case of
259 error. The terminating newline is not stripped.
261 This function is efficient only for buffered files. Avoid
262 readLine() for files that have been opened with the \c IO_Raw
265 \sa readBlock(), QTextStream::readLine()
268 int QFile::readLine( char *p, uint maxlen )
270 if ( maxlen == 0 ) // application bug?
272 #if defined(CHECK_STATE)
274 if ( !isOpen() ) { // file not open
275 qWarning( "QFile::readLine: File not open" );
278 if ( !isReadable() ) { // reading not permitted
279 qWarning( "QFile::readLine: Read operation not permitted" );
283 int nread; // number of bytes read
284 if ( isRaw() ) { // raw file
285 nread = QIODevice::readLine( p, maxlen );
286 } else { // buffered file
287 p = fgets( p, maxlen, fh );
289 nread = qstrlen( p );
293 setStatus(IO_ReadError);
301 Reads a line of text.
303 Reads bytes from the file until end-of-line is reached, or up to \a
304 maxlen bytes, and returns the number of bytes read, or -1 in case of
305 error. The terminating newline is not stripped.
307 This function is efficient only for buffered files. Avoid
308 readLine() for files that have been opened with the \c IO_Raw
311 Note that the string is read as plain Latin1 bytes, not Unicode.
313 \sa readBlock(), QTextStream::readLine()
316 int QFile::readLine( QString& s, uint maxlen )
318 QByteArray ba(maxlen);
319 int l = readLine(ba.data(),maxlen);
329 Reads a single byte/character from the file.
331 Returns the byte/character read, or -1 if the end of the file has been
334 \sa putch(), ungetch()
339 #if defined(CHECK_STATE)
340 if ( !isOpen() ) { // file not open
341 qWarning( "QFile::getch: File not open" );
344 if ( !isReadable() ) { // reading not permitted
345 qWarning( "QFile::getch: Read operation not permitted" );
352 if ( !ungetchBuffer.isEmpty() ) {
353 int len = ungetchBuffer.length();
354 ch = ungetchBuffer[ len-1 ];
355 ungetchBuffer.truncate( len - 1 );
359 if ( isRaw() ) { // raw file (inefficient)
361 ch = readBlock( buf, 1 ) == 1 ? buf[0] : EOF;
362 } else { // buffered file
363 if ( (ch = getc( fh )) != EOF )
366 setStatus(IO_ReadError);
372 \fn int QFile::writeBlock( const QByteArray& data )
375 Should be removed in 3.0
379 Writes the character \e ch to the file.
381 Returns \e ch, or -1 if some error occurred.
383 \sa getch(), ungetch()
386 int QFile::putch( int ch )
388 #if defined(CHECK_STATE)
389 if ( !isOpen() ) { // file not open
390 qWarning( "QFile::putch: File not open" );
393 if ( !isWritable() ) { // writing not permitted
394 qWarning( "QFile::putch: Write operation not permitted" );
398 if ( isRaw() ) { // raw file (inefficient)
401 ch = writeBlock( buf, 1 ) == 1 ? ch : EOF;
402 } else { // buffered file
403 if ( (ch = putc( ch, fh )) != EOF ) {
405 if ( ioIndex > length ) // update file length
408 setStatus(IO_WriteError);
415 Puts the character \e ch back into the file and decrements the index if it
418 This function is normally called to "undo" a getch() operation.
420 Returns \e ch, or -1 if some error occurred.
425 int QFile::ungetch( int ch )
427 #if defined(CHECK_STATE)
428 if ( !isOpen() ) { // file not open
429 qWarning( "QFile::ungetch: File not open" );
432 if ( !isReadable() ) { // reading not permitted
433 qWarning( "QFile::ungetch: Read operation not permitted" );
437 if ( ch == EOF ) // cannot unget EOF
440 if ( isSequentialAccess() && !fh) {
441 // pipe or similar => we cannot ungetch, so do it manually
446 if ( isRaw() ) { // raw file (very inefficient)
450 if ( writeBlock(buf, 1) == 1 )
454 } else { // buffered file
455 if ( (ch = ungetc(ch, fh)) != EOF )
458 setStatus( IO_ReadError );
464 static QCString locale_encoder( const QString &fileName )
466 return fileName.local8Bit();
470 static QFile::EncoderFn encoder = locale_encoder;
473 When you use QFile, QFileInfo, and QDir to access the filesystem
474 with Qt, you can use Unicode filenames. On Unix, these filenames
475 are converted to an 8-bit encoding. If you want to do your own
476 file I/O on Unix, you should convert the filename using this
477 function. On Windows NT, Unicode filenames are supported directly
478 in the filesystem and this function should be avoided. On Windows 95,
479 non-Latin1 locales are not supported at this time.
481 By default, this function converts to the local 8-bit encoding
482 determined by the user's locale. This is sufficient for
483 filenames that the user chooses. Filenames hard-coded into the
484 application should only use 7-bit ASCII filename characters.
486 The conversion scheme can be changed using setEncodingFunction().
487 This might be useful if you wish to give the user an option to
488 store in filenames in UTF-8, etc., but beware that such filenames
489 would probably then be unrecognizable when seen by other programs.
494 QCString QFile::encodeName( const QString &fileName )
496 return (*encoder)(fileName);
500 \enum QFile::EncoderFn
502 This is used by QFile::setEncodingFunction().
506 Sets the function for encoding Unicode filenames.
507 The default encodes in the locale-specific 8-bit encoding.
511 void QFile::setEncodingFunction( EncoderFn f )
517 QString locale_decoder( const QCString &localFileName )
519 return QString::fromLocal8Bit(localFileName);
522 static QFile::DecoderFn decoder = locale_decoder;
525 This does the reverse of QFile::encodeName().
527 \sa setDecodingFunction()
529 QString QFile::decodeName( const QCString &localFileName )
531 return (*decoder)(localFileName);
535 \enum QFile::DecoderFn
537 This is used by QFile::setDecodingFunction().
541 Sets the function for decoding 8-bit filenames.
542 The default uses the locale-specific 8-bit encoding.
544 \sa encodeName(), decodeName()
547 void QFile::setDecodingFunction( DecoderFn f )