A Complete Guide - C Programming Formatted File IO fprintf, fscanf
C Programming Formatted File I/O: fprintf and fscanf
C programming offers robust support for file operations, including reading from and writing to files using formatted I/O functions such as fprintf for output and fscanf for input. These functions enable developers to read and write data to files in a structured format, similar to the way printf and scanf handle standard input and output on the console. Here, we will delve into the details of fprintf and fscanf and illustrate their usage with examples.
fprintf
fprintf is used to write formatted data to a file. It works similarly to the printf function, but instead of writing to the standard output (console), it writes to a specified file stream. The function prototype is as follows:
int fprintf(FILE *stream, const char *format, ...);
- *FILE stream: A pointer to the file structure where data will be written. This file must be opened in write mode (
"w","a","wb","ab", etc.). - *const char format: A string that specifies the format of the data to be written. It can include both literal characters and format specifiers (e.g.,
%d,%f,%c). - ...: Variable number of arguments following the format string. These arguments are converted and formatted according to the format specifiers in the format string.
Format Specifiers:
%dfor signed integers%ufor unsigned integers%ffor floating-point numbers%eor%Efor exponential representation of floating-point numbers%cfor characters%sfor strings%pfor pointers%%for a literal percent sign
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
int number = 10;
float floatNumber = 10.76;
char string[] = "Hello, World!";
filePointer = fopen("example.txt", "w"); // Open file in write mode
if (filePointer == NULL) {
printf("Failed to open the file.\n");
return 1;
}
// Using fprintf to write data to the file
fprintf(filePointer, "Integer: %d\n", number);
fprintf(filePointer, "Float: %f\n", floatNumber);
fprintf(filePointer, "String: %s\n", string);
fclose(filePointer); // Close file
return 0;
}
fscanf
fscanf is the counterpart to fprintf; it reads formatted data from a file. Similar to scanf, fscanf reads data from a file stream and stores it in variables according to the format specifiers provided. The function prototype is as follows:
int fscanf(FILE *stream, const char *format, ...);
- *FILE stream: A pointer to the file structure from which data will be read. This file must be opened in read mode (
"r","rb", etc.). - *const char format: A string that specifies the format of the data to be read. It can include literal characters and format specifiers (e.g.,
%d,%f,%c). - ...: Variable number of pointers to variables where the read data will be stored. These pointers are associated with the format specifiers in the format string.
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
int number;
float floatNumber;
char string[100];
filePointer = fopen("example.txt", "r"); // Open file in read mode
if (filePointer == NULL) {
printf("Failed to open the file.\n");
return 1;
}
// Using fscanf to read data from the file
fscanf(filePointer, "Integer: %d\n", &number);
fscanf(filePointer, "Float: %f\n", &floatNumber);
fscanf(filePointer, "String: %s\n", string);
printf("Data read from file:\nInteger: %d\nFloat: %f\nString: %s\n", number, floatNumber, string);
fclose(filePointer); // Close file
return 0;
}
Important Considerations
File Opening Modes:
r: Open file for reading. File must exist.w: Open file for writing. If file exists, it is truncated (length set to zero). If file does not exist, it is created.a: Open file for appending. Data is written to the end of the file.rb,wb,ab: Binary versions ofr,w,a.
Error Handling:
- Always check if the file was opened successfully using
fopen. IffopenreturnsNULL, the file could not be opened. - After all file operations, close the file using
fcloseto free up resources.
- Always check if the file was opened successfully using
Buffering:
- Writing operations with
fprintfare buffered. To ensure data is written to the file immediately, usefflushto flush the buffer orfcloseto close the file.
- Writing operations with
Security:
- Avoid using
%swithfscanfwithout specifying a field width to prevent buffer overflow. Instead, use%NswhereNis the maximum number of characters to read.
- Avoid using
Multiple Line Reading:
fscanfstops reading a string when it encounters whitespace or a newline. For multi-line reading, consider usingfgetsorgetline.
Understanding and effectively using fprintf and fscanf is crucial for handling file I/O operations in C programming. These functions provide a powerful way to write and read data to and from files in a structured and formatted manner.
Online Code run
Step-by-Step Guide: How to Implement C Programming Formatted File IO fprintf, fscanf
Step-by-Step Example
Step 1: Understanding the Functions
fprintf: This function formats data and writes it to a file.- Syntax:
int fprintf(FILE *stream, const char *format, ...);
- Syntax:
fscanf: This function reads and parses formatted data from a file.- Syntax:
int fscanf(FILE *stream, const char *format, ...);
- Syntax:
Step 2: Writing Data to a File using fprintf
Let's start by creating a program that writes some data into a file using fprintf.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Open a file in write mode
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
perror("Failed to open file for writing");
return EXIT_FAILURE;
}
// Data to write
int age = 25;
double height = 5.9;
char name[] = "Alice";
// Write data to the file in a formatted manner
fprintf(file, "Name: %s\n", name);
fprintf(file, "Age: %d\n", age);
fprintf(file, "Height: %.2f feet\n", height);
// Close the file
fclose(file);
printf("Data written successfully to example.txt\n");
return EXIT_SUCCESS;
}
Explanation:
- Opening the File:
FILE *file = fopen("example.txt", "w");opens a file namedexample.txtin write mode. If the file does not exist, it creates a new one. - Writing Data:
fprintf(file, "Name: %s\n", name);writes formatted data to the file. The%sformat specifier tellsfprintfto insert a string at that position. - Closing the File:
fclose(file);is used to close the file after writing.
Step 3: Reading Data from a File using fscanf
Now, let's create a program that reads the data we just wrote back from the file using fscanf.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Open a file in read mode
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file for reading");
return EXIT_FAILURE;
}
// Variables to store data read from the file
int age;
double height;
char name[50];
// Read data from the file in a formatted manner
fscanf(file, "Name: %s", name);
fscanf(file, "Age: %d", &age);
fscanf(file, "Height: %lf feet", &height);
// Close the file
fclose(file);
// Print the data read from the file
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f feet\n", height);
return EXIT_SUCCESS;
}
Explanation:
- Opening the File:
FILE *file = fopen("example.txt", "r");opens the file in read mode. - Reading Data:
fscanf(file, "Name: %s", name);reads the formatted data into the variables. The%sformat specifier tellsfscanfto read a string,%dfor an integer, and%lffor a double. - Closing the File:
fclose(file);closes the file after reading. - Printing Data:
printfis used to display the data read from the file.
Step 4: Running the Programs
Compile the first program that writes data to
example.txt:gcc -o write_file write_file.c ./write_fileCompile the second program that reads data from
example.txt:gcc -o read_file read_file.c ./read_file
Summary
Writing Data:
- Use
fprintfto write formatted data to a file.
- Use
Reading Data:
- Use
fscanfto read and parse formatted data from a file.
- Use
File Handling:
- Always open a file using
fopen(). - Close the file using
fclose()after completing file operations.
- Always open a file using
Top 10 Interview Questions & Answers on C Programming Formatted File IO fprintf, fscanf
Top 10 Questions and Answers on C Programming: Formatted File I/O with fprintf and fscanf
1. What are fprintf and fscanf in C?
2. How do you use fprintf to write to a file?
You need a FILE* pointer to a file opened in write mode before using fprintf. The basic syntax is:
fprintf(FILE *stream, const char *format, ...);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Hello, world!\nNumber: %d\n", 42);
fclose(fp);
return 0;
}
This code writes "Hello, world!" followed by "Number: 42" to "example.txt".
3. How do you use fscanf to read from a file?
You need a FILE* pointer to a file opened in read mode before using fscanf. The syntax is similar to scanf:
int fscanf(FILE *stream, const char *format, ...);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char str[50];
int num;
fscanf(fp, "%s Number: %d", str, &num);
printf("Read string: %s\nRead number: %d\n", str, num);
fclose(fp);
return 0;
}
This reads the string "Hello, world!" and the number 42 from "example.txt".
4. What are the common format specifiers for fprintf and fscanf?
Common format specifiers include:
%d,%ifor integers.%ffor floating point numbers.%sfor strings.%cfor single characters.%xfor hexadecimal numbers.%ofor octal numbers.%ufor unsigned integers.%pfor pointers.
5. How does fprintf handle whitespace and newlines?
fprintf treats whitespace in the format string like any other character. To insert a newline, you can use \n. Extra spaces in the format string are output as a single space.
Example:
fprintf(fp, "Hello %s %d\n", "world", 123);
This outputs "Hello world 123" with extra spaces preserved and a newline at the end.
6. How does fscanf handle whitespace and newlines when reading a file?
fscanf ignores any whitespace (spaces, newlines, tabs) in the input file until it encounters a non-whitespace character that matches the specified format specifier. This behavior can vary depending on the format specifier used.
Example:
fscanf(fp, "%s %d", str, &num);
This would ignore any leading whitespace, then read a word into str, then any subsequent whitespace, and finally an integer into num.
7. How can you handle errors when using fprintf and fscanf?
After using fprintf or fscanf, always check for errors. fprintf returns the number of items successfully written, and fscanf returns the number of items successfully read. If the return value is less than the number of items expected, an error occurred.
Example:
int ret = fscanf(fp, "%d", &num);
if (ret != 1) {
printf("Error reading from file!\n");
}
8. What are the differences between fprintf and sprintf?
fprintf writes formatted data to a file pointed to by a FILE* pointer, while sprintf writes formatted data to a string.
Syntax:
fprintf(FILE *stream, const char *format, ...);int sprintf(char *str, const char *format, ...);
Example:
char str[100];
sprintf(str, "Hello, %s! Number: %d", "world", 55);
This stores "Hello, world! Number: 55" into the string str.
9. How can you append data to an already existing file using fprintf?
To append data to an existing file, open the file in append mode "a".
Example:
FILE *fp = fopen("example.txt", "a");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Appending line.\n");
fclose(fp);
This adds "Appending line." to the end of "example.txt" without overwriting its existing content.
10. How can you read a file line by line using fscanf or fgets?
While fscanf is not the most ideal for reading lines due to its whitespace handling, fgets is more suited for this task.
Using fgets:
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("Line: %s", buffer);
}
fclose(fp);
return 0;
}
fgets reads a line from the file into buffer up to sizeof(buffer) - 1 characters and includes the newline at the end of each line.
Using fscanf:
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char str[100];
while (fscanf(fp, "%99[^\n]%*c", str) == 1) {
printf("Line: %s\n", str);
}
fclose(fp);
return 0;
}
This uses fscanf with a format specifier that reads characters up to a newline and ignores the newline itself.
Login to post a comment.