Advanced Usage of fprintf and fscanf for Appending and Reading Files in C

Advanced Usage of fprintf and fscanf for Appending and Reading Files in C

In C programming, file operations are a very important part. Through files, we can persistently store data and also read data from them. In this article, we will focus on how to use <span>fprintf</span> and <span>fscanf</span> functions for appending and reading files.

File Open Modes

Before performing file operations, we need to understand the different open modes. The commonly used modes are:

  • <span>"r"</span>: Read-only mode, the file must exist.
  • <span>"w"</span>: Write-only mode, if the file exists, it is cleared; if it does not exist, it is created.
  • <span>"a"</span>: Append mode, data will be added after the existing content.
  • <span>"rb"</span>, <span>"wb"</span>, <span>"ab"</span>: Open the corresponding type of file in binary mode.

For our topic, we mainly focus on <span>"a"</span> (append) and <span>"r"</span> (read) modes.

Using <span>fprintf</span> for Appending

We can use the <span>fprintf</span> function to add content to a text file. Here is a simple example:

#include <stdio.h>
int main() {
    FILE *file;
    // Open or create a text file in append mode
    file = fopen("example.txt", "a");
    if (file == NULL) {
        perror("Unable to open or create file");
        return -1;
    }
    // Write a line of text to the file
    fprintf(file, "This is a new line.\n");
    // Close the file
    fclose(file);
    printf("Successfully added a line to example.txt.\n");
    return 0;
}

Code Explanation

  1. Open/Create File:

  • Use the <span>fopen()</span> function to open or create a text file named <span>example.txt</span> in “append” mode (<span>"a"</span>). If this operation fails, it will return <span>NULL</span>.
  • Error Handling:

    • If the file cannot be successfully opened or created, use <span>perror()</span> to output an error message and return -1 to indicate abnormal program termination.
  • Write Content:

    • Use <span>fprintf()</span> to format the string and output it to the specified text stream (i.e., our target document).
  • Close Document:

    • Finally, call <span>fclose()</span> to close the opened document to ensure that all buffered data is correctly saved and resources are released.

    Using <span>fscanf</span> for Reading

    Next, let’s see how to read data from the text we just modified. Here is the relevant code example:

    #include <stdio.h>
    int main() {
        FILE *file;        // Open an existing text file for reading
        file = fopen("example.txt", "r");        
        if (file == NULL) {
            perror("Unable to open the document to read");
            return -1;
        }
        char buffer[256];
        // Loop to read line by line until EOF (End Of File)
        while (fgets(buffer, sizeof(buffer), file)) {
            printf("%s", buffer);
        }
        // Close the document
        fclose(file);
        return 0;
    }

    Code Explanation

    1. Open Document:

    • Similarly, try to access the existing document named <span>example.txt</span> in “read-only” (<span>"r"</span>) mode by calling the <span>fopen()</span> function. If it fails, output an error message and exit the program.
  • Read Line by Line:

    • We use a loop structure combined with the <span>fgets()</span> function to read each record line by line and store it in a character array (<span>buffer</span>). This method will continue until it encounters the EOF marker, which stops the loop when there is no more data to read.
  • Print Results:

    • After successfully retrieving a line, it is immediately printed out so that the user can see all the content in the text document.
  • Close Document:

    • Finally, it is also necessary to call <span>fclose()</span> to release resources and ensure that all operations are completed correctly.

    Conclusion

    Through the above examples, we have learned how to effectively manage text data using standard library functions in C, including how to append new records to existing logs and how to extract information from logs. These basic skills are crucial for anyone looking to gain a deeper understanding of C and its applications. In practical development, you may encounter more complex data structures and requirements, but mastering this foundational knowledge is undoubtedly an important prerequisite for taking the first step.

    Leave a Comment