fwrite() Returns 0 When the Item Size Is 0

ID: Q79069

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a | 1.00 1.50

MS-DOS                      | OS/2            | WINDOWS
kbprg

The information in this article applies to:

SUMMARY

The "Microsoft C Optimizing Compiler: Run-Time Library Reference" for version 5.1, the Microsoft C versions 6.0, 6.0a, 6.0ax Advisor, and Microsoft C/C++ 7.0 and Visual C++ "Run-Time Library Reference" document the syntax for fwrite() as:

   size_t fwrite( const void *buffer,
                         size_t size,
                        size_t count,
                        FILE *stream)

The documentation also states the following about its return value:

   The fwrite() function returns the number of full items actually
   written, which may be less than <count> if an error occurs.

The function, as implemented by Microsoft, returns a 0 (zero) if the item size is 0, since the number of full items actually written is 0.

MORE INFORMATION

Section 4.9.8.2 of the ANSI standard documents the syntax for fwrite() as:

   size_t fwrite( const void *ptr,
                      size_t size,
                     size_t nmemb,
                     FILE *stream)

ANSI also states that:

   The fwrite() function returns the number of elements successfully
   written, which will be less than <nmemb> only if a write error is
   encountered.

ANSI does not state what the return value should be for a write of <nmemb> items of size 0. The return value would be dependent on the implementation of the compiler.

For example, if an item of size 0 is sent to test whether a file is write enabled, without actually writing anything to the file, the Microsoft implementation of the function will return a value of 0. This leaves a return value of 0 ambiguous; in this case it can be mistakenly interpreted as an error return.

The sample code below illustrates the ambiguity. The program output is:

   Result is 0.

Sample Code

/* Compile options needed: none
*/ 

#include<stdio.h>

#define SIZE 0
#define NUMBER_TO_WRITE 10

void main( void );

void main()
{
   int result;
   FILE *fp;

   fp = fopen( "c:\\test.tmp", "w+t" );
   result = fwrite( &result, SIZE, NUMBER_TO_WRITE, fp );

   printf("Result is %d.\n", result);

   fclose( fp );
}

NOTE: In Visual C++ for Windows NT, versions 1.0, 2.0 and 2.1, fwrite() returns the number elements written regardless of the size. The sample program in this article will return a 10.

Additional reference words: kbinf 5.10 6.00 6.00a 6.00ax 7.00 1.00 1.50 KBCategory: kbprg KBSubcategory: CRTIss Keywords : kb16bitonly

Last Reviewed: July 18, 1997