TQFile Class

Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# TQFile Class Reference

The TQFile class is an I/O device that operates on files. More...

Almost all the functions in this class are reentrant when TQt is built with thread support. The exceptions are setEncodingFunction(), setDecodingFunction(), and setErrorString().

`#include <ntqfile.h>`

Inherits TQIODevice.

List of all member functions.

## Public Members

- TQFile ()
- TQFile ( const TQString & name )
- ~TQFile ()
- TQString name () const
- void setName ( const TQString & name )
- typedef TQCString (* EncoderFn ) ( const TQString & fileName )
- typedef TQString (* DecoderFn ) ( const TQCString & localfileName )
- bool exists () const
- bool remove ()
- virtual bool open ( int m )
- bool open ( int m, FILE * f )
- bool open ( int m, int f )
- virtual void close ()
- virtual void flush ()
- virtual Offset size () const
- virtual bool atEnd () const
- virtual TQ_LONG readLine ( char * p, TQ_ULONG maxlen )
- TQ_LONG readLine ( TQString & s, TQ_ULONG maxlen )
- virtual int getch ()
- virtual int putch ( int ch )
- virtual int ungetch ( int ch )
- int handle () const
- TQString errorString () const

## Static Public Members

- TQCString encodeName ( const TQString & fileName )
- TQString decodeName ( const TQCString & localFileName )
- void setEncodingFunction ( EncoderFn f )
- void setDecodingFunction ( DecoderFn f )
- bool exists ( const TQString & fileName )
- bool remove ( const TQString & fileName )

## Important Inherited Members

- virtual TQByteArray readAll ()

## Protected Members

- void setErrorString ( const TQString & str )

## Detailed Description

The TQFile class is an I/O device that operates on files.

TQFile is an I/O device for reading and writing binary and text files. A TQFile may be used by itself or more conveniently with a TQDataStream or TQTextStream.

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 TQDataStream or TQTextStream, but you can read with readBlock() and readLine() and write with writeBlock(). TQFile 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 TQTextStream to read a text file line by line. It prints each line with a line number.

        TQStringList lines;
        TQFile file( "file.txt" );
        if ( file.open( IO_ReadOnly ) ) {
            TQTextStream stream( &file );
            TQString line;
            int i = 1;
            while ( !stream.atEnd() ) {
                line = stream.readLine(); // line of text excluding '\n'
                printf( "%3d: %s\n", i++, line.latin1() );
                lines += line;
            }
            file.close();
        }

Writing text is just as easy. The following example shows how to write the data we read into the string list from the previous example:

        TQFile file( "file.txt" );
        if ( file.open( IO_WriteOnly ) ) {
            TQTextStream stream( &file );
            for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
                stream << *it << "\n";
            file.close();
        }

The TQFileInfo class holds detailed information about a file, such as access permissions, file dates and file types.

The TQDir class manages directories and lists of file names.

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

See also TQDataStream, TQTextStream, and Input/Output and Networking.

## Member Type Documentation

### TQFile::DecoderFn

This is used by TQFile::setDecodingFunction().

### TQFile::EncoderFn

This is used by TQFile::setEncodingFunction().

## Member Function Documentation

### TQFile::TQFile ()

Constructs a TQFile with no name.

### TQFile::TQFile ( const TQString & name )

Constructs a TQFile with a file name name.

See also setName().

### TQFile::~TQFile ()

Destroys a TQFile. Calls close().

### bool TQFile::atEnd () const`[virtual]`

Returns true if the end of file has been reached; otherwise returns false. If TQFile has not been open()'d, then the behavior is undefined.

See also size().

Example: distributor/distributor.ui.h.

Reimplemented from TQIODevice.

### void TQFile::close ()`[virtual]`

Closes an open file.

The file is not closed if it was opened with an existing file handle. If the existing file handle is a `FILE*`, the file is flushed. If the existing file handle is an `int` file descriptor, nothing is done to the file.

Some "write-behind" filesystems may report an unspecified error on closing the file. These errors only indicate that something may have gone wrong since the previous open(). In such a case status() reports IO_UnspecifiedError after close(), otherwise IO_Ok.

See also open() and flush().

Examples: chart/chartform_files.cpp, distributor/distributor.ui.h, helpviewer/helpwindow.cpp, mdi/application.cpp, qdir/qdir.cpp, qwerty/qwerty.cpp, and xml/outliner/outlinetree.cpp.

Reimplemented from TQIODevice.

### TQString TQFile::decodeName ( const TQCString & localFileName )`[static]`

This does the reverse of TQFile::encodeName() using localFileName.

See also setDecodingFunction().

Example: distributor/distributor.ui.h.

### TQCString TQFile::encodeName ( const TQString & fileName )`[static]`

When you use TQFile, TQFileInfo, and TQDir to access the file system with TQt, you can use Unicode file names. On Unix, these file names are converted to an 8-bit encoding. If you want to do your own file I/O on Unix, you should convert the file name using this function. On Windows NT/2000, Unicode file names are supported directly in the file system and this function should be avoided. On Windows 95, non-Latin1 locales are not supported.

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.

The conversion scheme can be changed using setEncodingFunction(). This might be useful if you wish to give the user an option to store file names in UTF-8, etc., but be aware that such file names would probably then be unrecognizable when seen by other programs.

See also decodeName().

Example: distributor/distributor.ui.h.

### TQString TQFile::errorString () const

Returns a human-readable description of the reason of an error that occurred on the device. The error described by the string corresponds to changes of TQIODevice::status(). If the status is reset, the error string is also reset.

The returned strings are not translated with the TQObject::tr() or TQApplication::translate() functions. They are marked as translatable strings in the "TQFile" context. Before you show the string to the user you should translate it first, for example:

            TQFile f( "address.dat" );
            if ( !f.open( IO_ReadOnly ) {
                TQMessageBox::critical(
                    this,
                    tr("Open failed"),
                    tr("Could not open file for reading: %1").arg( tqApp->translate("TQFile",f.errorString()) )
                    );
                return;
            }

See also TQIODevice::status(), TQIODevice::resetStatus(), and setErrorString().

### bool TQFile::exists ( const TQString & fileName )`[static]`

Returns true if the file given by fileName exists; otherwise returns false.

Examples: chart/chartform.cpp, dirview/dirview.cpp, and helpviewer/helpwindow.cpp.

### bool TQFile::exists () const

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

Returns true if this file exists; otherwise returns false.

See also name().

### void TQFile::flush ()`[virtual]`

Flushes the file buffer to the disk.

close() also flushes the file buffer.

Reimplemented from TQIODevice.

### int TQFile::getch ()`[virtual]`

Reads a single byte/character from the file.

Returns the byte/character read, or -1 if the end of the file has been reached.

See also putch() and ungetch().

Reimplemented from TQIODevice.

### int TQFile::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 (ie. Unix systems, but not Windows) the handle can be used with TQSocketNotifier as well.

If the file is not open or there is an error, handle() returns -1.

See also TQSocketNotifier.

### TQString TQFile::name () const

Returns the name set by setName().

See also setName() and TQFileInfo::fileName().

### bool TQFile::open ( int m )`[virtual]`

Opens the file specified by the file name currently set, using the mode m. Returns true if successful, otherwise false.

The mode parameter m must be a combination of the following flags:

Flag | Meaning
--- | ---
IO_Raw | Raw (non-buffered) file access.
IO_ReadOnly | Opens the file in read-only mode.
IO_WriteOnly | Opens the file in write-only mode. If this flag is used with another flag, e.g. IO_ReadOnly or IO_Raw or IO_Append, the file is not truncated; but if used on its own (or with IO_Truncate), the file is truncated.
IO_ReadWrite | Opens the file in read/write mode, equivalent to `(IO_ReadOnly | IO_WriteOnly)`.
IO_Append | Opens the file in append mode. (You must actually use `(IO_WriteOnly | IO_Append)` to make the file writable and to go into append mode.) This mode is very useful when you want to write something to a log file. The file index is set to the end of the file. Note that the result is undefined if you position the file index manually using at() in append mode.
IO_Truncate | Truncates the file.
IO_Translate | Enables carriage returns and linefeed translation for text files under Windows.

The raw access mode is best when I/O is block-operated using a 4KB block size or greater. Buffered access works better when reading small portions of data at a time.

Warning: When working with buffered files, data may not be written to the file at once. Call flush() to make sure that the data is really written.

Warning: If you have a buffered file opened for both reading and writing you must not perform an input operation immediately after an output operation or vice versa. You should always call flush() or a file positioning operation, e.g. at(), between input and output operations, otherwise the buffer may contain garbage.

If the file does not exist and IO_WriteOnly or IO_ReadWrite is specified, it is created.

Example:

            TQFile f1( "/tmp/data.bin" );
            f1.open( IO_Raw | IO_ReadWrite );

            TQFile f2( "readme.txt" );
            f2.open( IO_ReadOnly | IO_Translate );

            TQFile f3( "audit.log" );
            f3.open( IO_WriteOnly | IO_Append );

See also name(), close(), isOpen(), and flush().

Examples: application/application.cpp, chart/chartform_files.cpp, distributor/distributor.ui.h, helpviewer/helpwindow.cpp, qdir/qdir.cpp, qwerty/qwerty.cpp, and xml/outliner/outlinetree.cpp.

Reimplemented from TQIODevice.

### bool TQFile::open ( int m, FILE * f )

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

Opens a file in the mode m using an existing file handle f. Returns true if successful, otherwise false.

Example:

        #include <stdio.h>

        void printError( const char* msg )
        {
            TQFile f;
            f.open( IO_WriteOnly, stderr );
            f.writeBlock( msg, tqstrlen(msg) );      // write to stderr
            f.close();
        }

When a TQFile is opened using this function, close() does not actually close the file, only flushes it.

Warning: If f is `stdin`, `stdout`, `stderr`, you may not be able to seek. See TQIODevice::isSequentialAccess() for more information.

See also close().

### bool TQFile::open ( int m, int f )

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

Opens a file in the mode m using an existing file descriptor f. Returns true if successful, otherwise false.

When a TQFile is opened using this function, close() does not actually close the file.

The TQFile 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 f is one of 0 (stdin), 1 (stdout) or 2 (stderr), you may not be able to seek. size() is set to `INT_MAX` (in limits.h).

See also close().

### int TQFile::putch ( int ch )`[virtual]`

Writes the character ch to the file.

Returns ch, or -1 if some error occurred.

See also getch() and ungetch().

Reimplemented from TQIODevice.

### TQByteArray TQIODevice::readAll ()`[virtual]`

This convenience function returns all of the remaining data in the device.

### TQ_LONG TQFile::readLine ( char * p, TQ_ULONG maxlen )`[virtual]`

Reads a line of text.

Reads bytes from the file into the char* p, until end-of-line or 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 IO_Raw flag.

See also readBlock() and TQTextStream::readLine().

Reimplemented from TQIODevice.

### TQ_LONG TQFile::readLine ( TQString & s, TQ_ULONG maxlen )

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

Reads a line of text.

Reads bytes from the file into string s, until end-of-line or maxlen bytes have been read, whichever occurs first. Returns the number of bytes read, or -1 if there was an error, e.g. end of file. Any terminating newline is not stripped.

This function is only efficient for buffered files. Avoid using readLine() for files that have been opened with the IO_Raw flag.

Note that the string is read as plain Latin1 bytes, not Unicode.

See also readBlock() and TQTextStream::readLine().

### bool TQFile::remove ()

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 TQFile::remove ( const TQString & fileName )`[static]`

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

Removes the file fileName. Returns true if successful, otherwise false.

### void TQFile::setDecodingFunction ( DecoderFn f )`[static]`

Warning: This function is not reentrant.

Sets the function for decoding 8-bit file names to f. The default uses the locale-specific 8-bit encoding.

See also encodeName() and decodeName().

### void TQFile::setEncodingFunction ( EncoderFn f )`[static]`

Warning: This function is not reentrant.

Sets the function for encoding Unicode file names to f. The default encodes in the locale-specific 8-bit encoding.

See also encodeName().

### void TQFile::setErrorString ( const TQString & str )`[protected]`

Warning: This function is not reentrant.

Sets the error string returned by the errorString() function to str.

See also errorString() and TQIODevice::status().

### void TQFile::setName ( const TQString & name )

Sets the name of the file to 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 at the time of the open() call.

Example:

            TQFile file;
            TQDir::setCurrent( "/tmp" );
            file.setName( "readme.txt" );
            TQDir::setCurrent( "/home" );
            file.open( IO_ReadOnly );      // opens "/home/readme.txt" under Unix

Note that the directory separator "/" works for all operating systems supported by TQt.

See also name(), TQFileInfo, and TQDir.

### Offset TQFile::size () const`[virtual]`

Returns the file size.

See also at().

Example: table/statistics/statistics.cpp.

Reimplemented from TQIODevice.

### int TQFile::ungetch ( int ch )`[virtual]`

Puts the character ch back into the file and decrements the index if it is not zero.

This function is normally called to "undo" a getch() operation.

Returns ch, or -1 if an error occurred.

See also getch() and putch().

Reimplemented from TQIODevice.

This file is part of the TQt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.