C fopen() Function Tutorial

In this section, we will learn what the fopen() function is and how it works in C.

Open a File in C: fopen() Function

The first step in order to work with a file in C programming is to open it!

In order to open a file, we use `fopen()` function.

The prototype of the function is in the `stdio.h` header file and so we need to include the file in order to work with the function.

C fopen() Function Syntax:

Here’s the prototype of the function:

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

C fopen() Function Parameters

As you can see, there are two parameters for this function:

  • The first parameter is the address of a character-string that defines the location of the file.
  • The second parameter is another character-string and that declares the mode in which the file should be opened. Mode is actually defining the type of operations that we can do on the file. For example, the mode `r` means we can only read the content of a file and not writing to it (Any write operation in this mode is ignored and if we attempt to do so the error indicator in the FILE-structure will be set).

In the table below, you can see the list of modes applicable to a file.

C fopen() Function Return Value

The returned value of this function is a pointer of type FILE. FILE actually is a structure that contains information about the opened file. This means the returned pointer doesn’t point to the actual file but to the memory space that contains information about the file.

This information includes:

  • File position indicator to specify the current position in the stream.
  • Indicators for error and end-of-file for the file.
  • A pointer to the beginning of the buffer where the file content will be copied to or written from.
  • A file identifier.
  • A count for the number of bytes actually copied into the buffer.

File Opening Modes in C: (File Operations in C)

List of modes:

Mode

Meaning

“r”

This mode is used to open a text file in reading mode.

Also, no-new file will be created if the file didn’t exist.

“w”

The mode is used to open a text file in writing mode.

Note: the content of the file (if any) will be removed and the file will have zero length, or a new file will be created if it didn’t exist.

“a”

The mode is used to open a file in writing mode.

Note: In this mode, the content of the target file will not truncate and any content we write to it will be appended to the end of the file.

A new file will be created if it doesn’t exist.

“r+”

In this mode, the file will be opened for both reading and writing and there’s no truncation on the file.

Note: both reading and writing happens at the starting point of the file.

Also, no-new file will be created if the file didn’t exist.

“w+”

The file will be opened for both reading and writing, but the difference from “r+” mode is that the content of the file will be truncated first or a new file will be created if it doesn’t exist.

“a+”

The file is opened for both reading and writing in this mode.

Also, for writing, content will be appended to the end of the file and so there’s no truncation.

Note: a new file will be created if it didn’t exist.

“rb”,”wb”,”ab”

“ab+”,”a+b”,

“wb+”,”w+b”,

“ab+”,”a+b”

Like the preceding modes, except they use binary mode instead of text mode.

“wx”,”wbx”,

“w+x”,”wb+x”, “w+bx”

(C11) Like the non-x modes, except they fail if the file already exists and they open a file in exclusive mode, if possible.

Example: opening a file in C

#include <stdio.h>
#include <stdlib.h>
int main() {

    //Call the the fopen function in order to open the file in read/write mode.
    FILE *file = fopen("G:/fileOne.txt","a+");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        exit(EXIT_FAILURE);
    }

    char c;
    while ((c = getc(file))!=EOF){
        printf("%c",c);
    }

    fputs("\n This is the last line of the file",file);

    rewind(file);
    while ((c = getc(file))!=EOF){
        printf("%c",c);
    }
    fclose(file);


    printf("\nDone\n");
    return 0;
}

Output:

The C-language is one of the coolest languages of all time.

The C-language is one of the coolest languages of all time.

This is the last line of the file

Done

In this example, the `fileOne` is opened in `a+` mode and so we can read as well as write to the file.

Note: reading from this file starts at the beginning, but writing will append to the end of the file.

At first we checked to see if the file is opened correctly by checking the returned pointer of the call to the `fopen` function in the `if-statement` (The `fopen` function will return NULL in case of a problem).

Then we looped through the content of the file to get all the content and printed them to the output. (Read the getc() function to learn more about the function)

After that, we wrote a character-string to the file via the call to fputs() function. Because the file is opened in the appending mode, the character-string in this function will be appended to the end of the file.

We then called the rewind function in order to start reading from the starting point of the file and next the program looped again to get the content of the file. This is because we want to see if the last character-string appended is actually added to the end of the file or not.

As the result shows, the new content is successfully appended to the end of the file.

Of course, at the end, we called the `fclose` function in order to close the file and release the memory allocated to it.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies