Microsoft KB Archive/79069

{|
 * width="100%"|

fwrite Returns 0 When the Item Size Is 0

 * }

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: - The C Run-time (CRT), included with: - Microsoft C for MS-DOS, versions 5.1, 6.0, 6.0a, and 6.0ax - Microsoft C for OS/2, versions 5.1, 6.0, and 6.0a - Microsoft C/C++ for MS-DOS, version 7.0 - Microsoft Visual C++ for Windows, versions 1.0 and 1.5 -- SUMMARY ======= The &quot;Microsoft C Optimizing Compiler: Run-Time Library Reference&quot; for version 5.1, the Microsoft C versions 6.0, 6.0a, 6.0ax Advisor, and Microsoft C/C++ 7.0 and Visual C++ &quot;Run-Time Library Reference&quot; 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 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 only if a write error is encountered. ANSI does not state what the return value should be for a write of 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 #define SIZE 0 #define NUMBER_TO_WRITE 10 void main( void ); void main { int result; FILE *fp; fp = fopen( &quot;c:\\test.tmp&quot;, &quot;w+t&quot; ); result = fwrite( &result, SIZE, NUMBER_TO_WRITE, fp ); printf(&quot;Result is %d.\n&quot;, 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

Issue type :

Technology : kbVCsearch kbAudDeveloper kbCRT