INF: fwrite() Will Return 0 If the Item Size Is 0

ID Number: Q79069

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

The "Microsoft C Optimizing Compiler: Run-Time Library Reference" for

version 5.1, the Microsoft C versions 6.0, 6.0a, 6.0ax, and 7.0 Advisor,

and the QuickC versions 2.5 and 2.51 Advisor 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 );

if( result == 0 )

printf( "Result is 0.\n" );

else printf( "Result is not 0.\n" );

fclose( fp );

}

Additional reference words: 5.10 6.00 6.00a 6.00ax 7.00 2.50