Microsoft KB Archive/39602

{| = INFO: Wrong Syntax for fopen Mode Argument Returns NULL Value =
 * width="100%"|

Article ID: Q39602

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, 6.0ax - Microsoft C/C++ for MS-DOS, version 7.0 - Microsoft Visual C++ for Windows, versions 1.0, 1.5, 1.51, 1.52 - Microsoft Visual C++, 32-bit Edition, versions 1.0, 2.0, 2.1, 4.0, 5.0

SUMMARY
In the second argument to the fopen function, if the specification of the mode character t (text) or b (binary) is before the file-access type r (read), w (write), or a (append), no compilation errors occur. However, at run-time, fopen fails to open the file and returns NULL.

The Visual C++ Books Online and the &quot;Microsoft C/C++ Compiler Run-Time Library Reference&quot; state that the mode character is to be appended to the character string for the type argument. If, instead, the mode character is placed before the beginning of the type argument, then fopen fails. An example follows.

Please note that the string that is passed as the second parameter to fopen could be a variable string as well as a constant string. Because the variable string could be constructed at run-time, it is impossible to check for this error at compile time.

MORE INFORMATION
The program below demonstrates this behavior. It prints &quot;failed&quot; and does not open a file. If the second argument to fopen is changed to &quot;wt&quot;, then it prints &quot;succeeded&quot; and the file is opened.

Sample Code
/* Compile options needed: none */

#include   FILE *s; void main(void); void main(void) {    if ((s = fopen(&quot;test.dat&quot;,&quot;tw&quot;)) == NULL) printf(&quot;fopen failed\n&quot;); else printf(&quot;fopen succeeded\n&quot;); } Additional query words: 8.00 8.00c 9.00 9.10 Keywords         : kbCRT kbVC Version          : MS-DOS:5.1,6.0,6.00a,6.00ax,7.0;  WINDOWS:1.0,1.5,1.51,1.52; WINDOWS NT:1.0,2.0,2.1,4.0,5.0 Platform         : MS-DOS NT WINDOWS Issue type       : kbinfo
 * }