fopen function in C Programming

fopen function

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

The fopen () function opens a file whose name is pointed to by 'filename' and returns the stream that is associated with it. The type of operation that will be allowed on the file are defined by the vale of mode. The legal values of modes are shown in the following table.

File Type Meaning
"r" Open an existing file for reading only
"w" Open a new file for writing only. If a file with the specified file-name currently exists, it will be destroyed and a new file created in its place.
"a" Open an existing file for appending (i.e., for adding new information at the end of the file). If a file with the specified file-name currently does not exist, a new file will be created.
"r+" Open an existing file for both reading and writing.
"w+" Open a new file for both reading and writing. If a file with the specified file-name currently exists, it will be destroyed and a new file created in its place.
"a+" Open an existing file for both reading and appending. If a file with the specified file-name currently does not exist, a new file will be created.

If fopen () is successful in opening the specified file, a FILE pointer is returned. If the file cannot be opened, a NULL pointer is required. The following code uses fopen () to open a file named TEST for output.

FILE *fptr;
fptr = fopen("TEST","w"); 

Although the preceding code is technically correct, the following code fragment illustrates the correct method of opening the file.

FILE *fptr;
if ((fptr = fopen ("TEST","w"))==NULL)
    {
    printf ("Cannot open file\n");
     exit (1);
     } 

This method detects any error in opening a file, such as write-protected or a full disk before attempting to write to it. If no file by that name exists, one will be created. Opening a file for read operations require that the file exists.

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!