7.3. fopen modes

“r” – text file for read.

“w” – text file for write.

“a” – text file for append.

“r+” – text file for read and write.

“a+” – text file for append and read.

“rb” – binary file for read.

“wb” – binary file for write.

“ab” – binary file for append and write.

“rb+” – binary file for read and write.

“ab+” – binary file for append and read.

In read-write mode, reading may not directly follow output unless EOF is reached or a call to one of the file positioning functions fseek(), fsetpos(), rewind() has occurred.

Similarly, writing may not directly follow reading without first making a call to one of fflush(), fseek(), fsetpos(), rewind().

7.4. Safe fopen

Always test the result of fopen().

FILE *fp;

if ((fp = fopen("filename", mode)) == NULL) {
   fprintf(stderr, "cannot open filename" );
   return 1;             // in Unix: exit(1);
}