fopen() Function in C

Introduction

fopen Definition

To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

  FILE *fopen(const char *filename, const char *mode);

fopen modes

  • r - open for reading.
  • w - open for writing (file need not exist).
  • a - open for appending (file need not exist).
  • r+ - open for reading and writing, start at beginning.
  • w+ - open for reading and writing (overwrite file).
  • a+ - open for reading and writing (append if file exists).

Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer.

Example of using fopen:

FILE *fp;
fp=fopen("c:\\test.txt", "r");