fprintf() and fscanf() in C

In C, fprintf() and fscanf() are functions used for writing to and reading from files, respectively. These functions provide a way to handle file I/O with formatted data.

Declaration and Syntax

                        
FILE *fopen(const char *filename, const char *mode);
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
                        
                    

The fprintf() function is used to write formatted data to a file, while fscanf() is used to read formatted data from a file.

Example: Writing and Reading Data Using `fprintf()` and `fscanf()`

                        
#include <stdio.h>
int main() 
{
    // Writing to a file using fprintf
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Unable to open file for writing.\n");
        return 1;
    }

    fprintf(file, "Name: John Doen");
    fprintf(file, "Age: %d\n", 30);
    fprintf(file, "Salary: %.2f\n", 50000.75);

    fclose(file);

    // Reading from the file using fscanf
    file = fopen("output.txt", "r");
    if (file == NULL) {
        printf("Unable to open file for reading.\n");
        return 1;
    }         
        
    char name[50];
    int age;
    float salary;

    fscanf(file, "Name: %s\n", name);
    fscanf(file, "Age: %d\n", &age);
    fscanf(file, "Salary: %f\n", &salary);

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);
    printf("Salary: %.2f\n", salary);

    fclose(file);      
    return 0;
}
                        
                    

Output:

Name: John Doe
Age: 30
Salary: 50000.75

File I/O Details

In the example above:

Memory Usage

The memory used for file operations depends on the file size, and the system allocates buffers to handle the reading and writing processes efficiently.

Difference Between fprintf() and fscanf()

Aspect fprintf() fscanf()
Function Purpose Write formatted data to a file. Read formatted data from a file.
Usage Used to output data to a file. Used to input data from a file.
Return Type Returns the number of characters written. Returns the number of items successfully read.

Key Points