FOPEN in C: How to Open a File to Read,Write, and Modify

fopencThe C language was developed in the 1970s for the UNIX operating system by Dennis Ritchie and Ken Thompson. It is a standard program language that was (and still is) wildly popular for a large range of applications, especially in embedded systems. You can take a sneak peak at this course that shows you how to create iOS applications with C

C language is relevant today because it is the mother language of all programming languages – almost all modern programming languages are based on C. A solid base in this language enables you to grasp other newer languages faster.

In today’s article we’ll show you how to open a file in C, and how you can use some basic file operations to read, modify and write a file. You need to have a basic working knowledge of C. Beginners need not be afraid. This special course to help get you on your feet and programming in C pretty fast.

File Handle in C

C lets you handle large chunks of data that could be numbers, text, or just any information, in the form of files. C has special handles to be used to point to files, along with a host of specially designed library functions to handle almost any possible kind of file transaction. To access a file in C, you need to use a file handle or pointer. The syntax for this is

File * file_ptr;

Here the opening “File” specifies the type of the pointer, and file_ptr is the name of the pointer variable.

Opening a File

So now that you have a file handle, how do you actually open a file? C has a special library function ‘fopen’, that let’s you do this easily. Here’s the syntax

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

The parameters used here are:

  • char *filename: This is the name of the file you want to open, in plain English. Rather, it is a character pointer that points to the name of the file stored in a character array.
  • char *mode: This is a C string (again a character pointer) pointer, that specifies the file access mode. You have quite a few options of the modes, that let you choose which way you want to open the file.
ModeWhat it means
“r”Only open a file to read. The file must exist before hand. Do not allow any changes to the file.
“w”Create a new file and write to it. If a file with the same name already exists, overwrite it – rather, erase the existing file and create a new one.
“a”Append to the end of a file. If the file does not exist, create a new one and write to it.
“r+”Open an existing file. Allow both read and write operations to this file. Note – file must exist a priori.
“w+”Create an empty file. Allow both reading and writing.
“a+”Open an existing file. Allow both reading and writing.

Note that the return value here is of type “file *”. This is actually the file handle we spoke of earlier. You should save this file handle safely in a variable. You’ll need it to access the file for any future read or write operation.

Example: Open and Write to a file

#include <stdio.h>
#include <stdlib.h>
int main()
{
   FILE * file_ptr;
   file_ptr = fopen ("file1.txt", "w+");
   fprintf(file_ptr, "%s %s %s %d", "We", "are", "in", 2014);
   fclose(file_ptr);
   return(0);
}

In this example, we open a file “file1.txt” and then we use the fprintf functions to write into this file. Note that we have to pass the file handle “file_ptr” to this function. That’s how it knows which file to write into. The strings in the double quotes, are the text to be written into this file. So what have we done in main? We’ve effectively created a file “file1.txt” and we’ve written the following text into it

We are in 2014

To learn more about functions like fprintf, you may want to check out this C course here.

Example: Open and Read from a File

#include <stdio.h>
#include <stdlib.h>
int main()
{
   FILE * file_ptr;
   int c;
   file_ptr = fopen ("file1.txt", "w+");
   while(1)
   {
      c = fgetc(file_ptr);
      if( feof(file_ptr) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(file_ptr);
   return(0);
}

What have we done here? We open the file “file1.txt” like in the earlier example. Then in a while() loop, we read each character from the file, and print it on the screen. We repeat this until we reach the end of the file. Quite simple, isn’t it?

Other File Operations

As you’ve seen in the above examples, C has a bunch of other functions you’re going to need to be able to read from a file or write into a file. Let’s quickly go through some of the most useful ones.

  • Fclose(): This is the opposite of fopen(). You should always call this once you’re done working with the file, or at the very least, when you’re exiting your program. If you leave the file handle unclosed, you’ll end up eating away your system memory.
  • Fprintf() : You probably remember the common printf() function. Fprintf() is the humble cousin, that you have to use to write into files.
  • Fgetc() : Again, like the getc() function, this one is used to get or read a character from a file.
  • Feof() : This function returns true, once you reach end of file. Note that you have to use this in a loop to actually get through the file to the end.

In this tutorial, we’ve just covered the most basic file operations. There’s a lot more waiting to be explored. You should probably check out our intermediate C course and try out some examples for yourself!