Function FWrite() Foundation

Writes a character string into an open file.

Syntax
FWrite( <nHandle>, <cString>, [<nBytes>] ) --> nBytesWritten
Parameters
<nHandle>
<nHandle> is an integer numeric value returned from either FCreate() or FOpen(). It is the file handle for the file provided by the operating system.
Alternatively, constants defined in FILEIO.CH can be specified for <nHandle>. They indicate a standard device.
Predefined file handles for standard devices
Constant Description
FH_STDIN Standard input
FH_STDOUT Standard output
FH_STDERR *) Standard error
  1. Not supported by Windows 95
<cString>
<cString> is the character string written into the file.
<nBytes>
<nBytes> is an integer numeric value which determines the number of characters written into the file from <cString>. If <nBytes>is missing, all of <cString> is written into the file.
Return

FWrite() returns an integer numeric value indicating the number of bytes actually written into the file. When the return value is less than <nBytes>, either an error occurred during the write operation or the memory capacity of the storage media is exhausted.

Description

The low level file function FWrite() writes a character string into an open file. The write operation begins at the current position of the file pointer. By specifying <nBytes>, part or all of the character string <cString> can be written into the file. The return value of FWrite() corresponds to the number of bytes actually written to the file. If the value is not the same as <nBytes>, an error occurred which can be diagnosed using the function FError().

Note that FWrite() does not automatically truncate existing file contents. If a short character is inserted in a file, the file pointer is advanced to the end of the insertion by FWrite(), but the rest of the file remains unchanged.

Examples
Copy files with FRead() and FWrite()

// In the example the function FCopy() is implemented 
// as a user-defined function with FRead() and FWrite(). 

#include "Fileio.ch" 

#define BUFFER_SIZE  2^16 

PROCEDURE Main 

   ? FCopy( "OLDFILE.DOC", "NEWFILE.DOC" ) 

RETURN 

FUNCTION FCopy( cSourceFile, cTargetFile ) 
   LOCAL nSource, nTarget, cBuffer, nBytes 

   IF ( nSource := FOpen( cSourceFile, FO_READ ) ) == -1 
      ? "File cannot be opened:",cSourceFile 

   ELSEIF ( nTarget := FCreate( cTargetFile, FC_NORMAL ) ) == -1 

      FClose( nSource ) 
      ? "File cannot be opened:", cTargetFile 

   ENDIF 

   cBuffer := Space( BUFFER_SIZE ) 
   nBytes  := BUFFER_SIZE 

   DO WHILE FError() == 0 .AND. nBytes > 0 
      nBytes := FRead( nSource, @cBuffer, BUFFER_SIZE ) 
      FWrite( nTarget, Left(cBuffer, nBytes) ) 
   ENDDO 

   FClose( nSource ) 
   FClose( nTarget ) 

RETURN FError() 

Feedback

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.