Open a File for Reading and Writing in C

To open a file for reading and writing in C, you can use the fopen() function from the standard I/O library with mode strings such as "r+", "w+", or "a+" depending on your needs.

In this tutorial, we will explain multiple scenarios and examples to help beginners understand how to work with files in C.


Example 1: Opening an Existing File using "r+" Mode

This example demonstrates how to open an existing file for both reading and writing using the "r+" mode. We will attempt to read a line from the file and then append some text at the current file pointer position.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Open an existing file "example.txt" in read and write mode ("r+")
    FILE *fp = fopen("example.txt", "r+");
    if (fp == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    // Read a line from the file
    char buffer[100];
    if (fgets(buffer, 100, fp) != NULL) {
        printf("File content: %s\n", buffer);
    }
    
    // Append text at the current file pointer position
    fputs(" Appending text.", fp);
    
    fclose(fp);
    return 0;
}

Explanation:

  1. The program includes the standard I/O header <stdio.h> and <stdlib.h> for necessary functions.
  2. fopen("example.txt", "r+") opens an existing file in read and write mode. The "r+" mode requires that the file already exists.
  3. The if (fp == NULL) block checks if the file was opened successfully. If not, an error message is printed and the program exits.
  4. fgets(buffer, 100, fp) reads up to 99 characters (plus the null terminator) from the file into the buffer.
  5. fputs(" Appending text.", fp) writes additional text to the file starting at the current position of the file pointer.
  6. fclose(fp) closes the file to free system resources.

Output:

File content: [Existing file content...]

Example 2: Creating and Opening a File using "w+" Mode

This example shows how to open a file for reading and writing using the "w+" mode. In this mode, if the file exists, it is truncated to zero length; if it does not exist, a new file is created.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Open (or create) a file "newfile.txt" in write and read mode ("w+")
    FILE *fp = fopen("newfile.txt", "w+");
    if (fp == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    // Write a string to the file
    fputs("Hello, world!\n", fp);
    
    // Move the file pointer back to the beginning for reading
    rewind(fp);
    
    // Read the content just written
    char buffer[100];
    if (fgets(buffer, 100, fp) != NULL) {
        printf("File content: %s", buffer);
    }
    
    fclose(fp);
    return 0;
}

Explanation:

  1. The program opens "newfile.txt" in "w+" mode using fopen(). This mode creates a new file or truncates an existing file.
  2. The fputs() function writes the string "Hello, world!\n" to the file.
  3. rewind(fp) resets the file pointer to the beginning of the file so that we can read the content we just wrote.
  4. fgets(buffer, 100, fp) reads the content from the file into the buffer array.
  5. The content is then printed using printf(), and finally the file is closed with fclose(fp).

Output:

File content: Hello, world!

Example 3: Appending to a File using "a+" Mode

This example illustrates how to open a file in append mode using "a+". This mode allows you to read the existing content and always writes new data at the end of the file.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Open (or create) a file "appendfile.txt" in append and read mode ("a+")
    FILE *fp = fopen("appendfile.txt", "a+");
    if (fp == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    // Move file pointer to the beginning to read existing content
    rewind(fp);
    
    char buffer[200];
    printf("Existing file content:\n");
    while (fgets(buffer, 200, fp) != NULL) {
        printf("%s", buffer);
    }
    
    // Append new text to the file
    fputs("New appended line.\n", fp);
    
    fclose(fp);
    return 0;
}

Explanation:

  1. The file "appendfile.txt" is opened in "a+" mode using fopen(). This mode allows both reading and appending.
  2. rewind(fp) is used to move the file pointer to the beginning so that the existing content can be read.
  3. A while loop with fgets() reads and prints each line of the existing file content.
  4. fputs("New appended line.\n", fp) writes a new line at the end of the file.
  5. The file is then closed with fclose(fp) to save changes and free resources.

Output:

Existing file content:
[Content previously in appendfile.txt, if any]
New appended line.

Conclusion

In this tutorial, we covered how to open files for reading and writing in C using different modes:

  1. "r+" Mode: Opens an existing file for both reading and writing without truncating the file.
  2. "w+" Mode: Opens a file for reading and writing, creating a new file or truncating an existing file.
  3. "a+" Mode: Opens a file for reading and appending, allowing you to add data to the end of the file while still reading its content.