INFO: Wrong Syntax for fopen Mode Argument Returns NULL Value

Last reviewed: August 26, 1997
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 "Microsoft C/C++ Compiler Run-Time Library Reference" 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 "failed" and does not open a file. If the second argument to fopen is changed to "wt", then it prints "succeeded" and the file is opened.

Sample Code

   /* Compile options needed: none
   */

   #include <stdio.h>
   FILE *s;
   void main(void);
   void main(void)
   {
     if ((s = fopen("test.dat","tw")) == NULL)
       printf("fopen failed\n");
     else
       printf("fopen succeeded\n");
   }


Additional query words: 8.00 8.00c 9.00 9.10
Keywords : CRTIss
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


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: August 26, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.