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
Age: 30
Salary: 50000.75
File I/O Details
In the example above:
- The file `output.txt` is created (if it doesn't already exist) for writing with `fopen()`. The mode `"w"` opens the file for writing, and if the file already exists, it is truncated.
- Formatted data is written to the file using `fprintf()`.
- The file is closed using `fclose()` after writing.
- To read the data back, the file is opened in read mode `"r"`, and the data is read using `fscanf()`.
- We read the name, age, and salary from the file and display them on the screen.
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
- fprintf() is used for writing formatted data to a file.
- fscanf() is used for reading formatted data from a file.
- Both functions are part of the standard C library and require the inclusion of the
<stdio.h>
header file. - When using these functions, always ensure proper file handling with `fopen()` and `fclose()` to avoid resource leaks.