fopen Function

Opens a file.

Attention: This function is not implemented by MPLAB XC8.

Include

<stdio.h>

Prototype

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

Arguments

filename
name of the file
mode
type of access permitted

Return Value

Returns a pointer to the open stream. If the function fails, a null pointer is returned.

Remarks

The following are types of file access:

r Opens an existing text file for reading.
w Opens an empty text file for writing (an existing file is overwritten).
a Opens a text file for appending (a file is created if it doesn’t exist).
rb Opens an existing binary file for reading.
wb Opens an empty binary file for writing (an existing file is overwritten).
ab Opens a binary file for appending (a file is created if it doesn’t exist).
r+ Opens an existing text file for reading and writing.
w+ Opens an empty text file for reading and writing (an existing file is overwritten).
a+ Opens a text file for reading and appending (a file is created if it doesn’t exist).
r+b or rb+ Opens an existing binary file for reading and writing.
w+b or wb+ Opens an empty binary file for reading and writing (an existing file is overwritten.)
a+b or ab+ Opens a binary file for reading and appending (a file is created if it doesn’t exist).

This function requires a heap.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#include <stdio.h>

int main(void)
{
  FILE *myfile1, *myfile2;
  int y;
  if ((myfile1 = fopen("afile1", "r")) == NULL)
    printf("Cannot open afile1\n");
  else
  {
    printf("afile1 was opened\n");
    y = fclose(myfile1);
    if (y == EOF)
      printf("afile1 was not closed\n");
    else
      printf("afile1 was closed\n");
  }
  if ((myfile1 = fopen("afile1", "w+")) == NULL)
    printf("Second try, cannot open afile1\n");
  else
  {
    printf("Second try, afile1 was opened\n");
    y = fclose(myfile1);
    if (y == EOF)
      printf("afile1 was not closed\n");
    else
      printf("afile1 was closed\n");
  }
  if ((myfile2 = fopen("afile2", "a+")) == NULL)
    printf("Cannot open afile2\n");
  else
  {
    printf("afile2 was opened\n");
    y = fclose(myfile2);
    if (y == EOF)
      printf("afile2 was not closed\n");
    else
      printf("afile2 was closed\n");
  }
}

Example Output

Cannot open afile1
Second try, afile1 was opened
afile1 was closed
afile2 was opened
afile2 was closed

Example Explanation

afile1 must exist before it can be opened for reading (r) or the fopen function will fail.

If the fopen function opens a file for writing (w+) it does not have to exist, it will be created and then opened. If the file does exist, it cannot be overwritten and will be appended.