Reading from and Writing to Files in C function’s
When working with files in C programming, two key operations are reading from and writing to files. These operations allow your programs to store data permanently and retrieve it later. C provides several functions for reading and writing, each suited to different needs.
At SamagraCS Educational Technology, we believe in providing simple, practical explanations to help you understand how to read from and write to files using various functions in C.
Overview of Functions for Reading and Writing Files
Here are the main functions used to read from and write to files in C:
- Writing to Files:
fprintf()
fputs()
fwrite()
- Reading from Files:
fscanf()
fgets()
fread()
Each function serves a slightly different purpose, whether you’re dealing with text or binary data, or reading/writing line by line, character by character, or in blocks.
1. Writing to Files in C
There are several ways to write data to a file. Let’s explore the most commonly used functions.
a) fprintf()
– Formatted Output to a File
The fprintf()
function is used to write formatted text to a file, similar to how printf()
works for console output.
Syntax:
int fprintf(FILE *filePointer, const char *format, ...);
- filePointer: A pointer to the file where data will be written.
- format: A format string (like the one used with
printf()
) that specifies the data format.
Example:
FILE *filePointer;
filePointer = fopen("students.txt", "w");
if (filePointer == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(filePointer, "Name: Pawan Jaiswal\n");
fprintf(filePointer, "Grade: 90\n");
fclose(filePointer);
This will write the formatted data (“Name: Pawan Jaiswal” and “Grade: 90”) to the file students.txt
.
b) fputs()
– Write a String to a File
The fputs()
function is used to write a string to a file. Unlike fprintf()
, it does not use a format string.
Syntax:
int fputs(const char *str, FILE *filePointer);
- str: The string to write to the file.
- filePointer: A pointer to the file.
Example:
FILE *filePointer;
filePointer = fopen("message.txt", "w");
if (filePointer == NULL) {
printf("Error opening file!\n");
return 1;
}
fputs("Welcome to SamagraCS Educational Technology!\n", filePointer);
fclose(filePointer);
This will write the string to message.txt
.
c) fwrite()
– Write Binary Data to a File
The fwrite()
function is used to write binary data to a file. It writes data in blocks, making it suitable for writing arrays or structures.
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *filePointer);
- ptr: A pointer to the data you want to write.
- size: The size of each element to write.
- count: The number of elements to write.
- filePointer: A pointer to the file.
Example:
FILE *filePointer;
int numbers[] = {1, 2, 3, 4, 5};
filePointer = fopen("numbers.bin", "wb");
if (filePointer == NULL) {
printf("Error opening file!\n");
return 1;
}
fwrite(numbers, sizeof(int), 5, filePointer); // Write the array to the file
fclose(filePointer);
This will write the binary data of the numbers
array to numbers.bin
.
2. Reading from Files in C
Now, let’s look at the functions used to read data from a file.
a) fscanf()
– Formatted Input from a File
The fscanf()
function reads formatted data from a file, similar to how scanf()
works for console input.
Syntax:
int fscanf(FILE *filePointer, const char *format, ...);
- filePointer: A pointer to the file.
- format: A format string (similar to
scanf()
).
Example:
FILE *filePointer;
char name[50];
int grade;
filePointer = fopen("students.txt", "r");
if (filePointer == NULL) {
printf("Error opening file!\n");
return 1;
}
fscanf(filePointer, "Name: %s\n", name);
fscanf(filePointer, "Grade: %d\n", &grade);
printf("Student Name: %s\n", name);
printf("Student Grade: %d\n", grade);
fclose(filePointer);
This will read the name and grade from the students.txt
file and print them to the console.
b) fgets()
– Read a String from a File
The fgets()
function reads a line of text from a file. It reads until a newline character is encountered or until the specified number of characters is reached.
Syntax:
char *fgets(char *str, int n, FILE *filePointer);
- str: The buffer to store the read string.
- n: The maximum number of characters to read.
- filePointer: A pointer to the file.
Example:
FILE *filePointer;
char buffer[100];
filePointer = fopen("message.txt", "r");
if (filePointer == NULL) {
printf("Error opening file!\n");
return 1;
}
fgets(buffer, 100, filePointer);
printf("File content: %s", buffer);
fclose(filePointer);
This will read and print the first line of text from message.txt
.
c) fread()
– Read Binary Data from a File
The fread()
function reads binary data from a file. It reads data in blocks, making it suitable for reading arrays or structures.
Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE *filePointer);
- ptr: A pointer to the buffer where the data will be stored.
- size: The size of each element to read.
- count: The number of elements to read.
- filePointer: A pointer to the file.
Example:
FILE *filePointer;
int numbers[5];
filePointer = fopen("numbers.bin", "rb");
if (filePointer == NULL) {
printf("Error opening file!\n");
return 1;
}
fread(numbers, sizeof(int), 5, filePointer); // Read the array from the file
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
fclose(filePointer);
This will read the binary data from numbers.bin
and print the array.
Best Practices for File I/O in C
- Always check if the file was opened successfully: Always check if
fopen()
returnsNULL
to avoid crashes. - Close the file after reading or writing: Use
fclose()
to properly close the file and free resources. - Use the correct mode: Make sure you use the appropriate file mode (
"r"
,"w"
,"rb"
,"wb"
) depending on whether you’re working with text or binary data. - Use buffers for efficiency: When reading or writing large amounts of data, using a buffer (like
fgets()
,fwrite()
, orfread()
) can improve efficiency.
Reading from and writing to files is an essential part of C programming, allowing you to store and retrieve data efficiently. Whether you’re working with text files or binary data, the C standard library provides powerful functions to handle file I/O.
At SamagraCS Educational Technology, we believe in breaking down these concepts into easy-to-understand steps. Practice using fprintf()
, fscanf()
, fputs()
, fgets()
, fwrite()
, and fread()
to get comfortable with file I/O in C.
For any questions, feel free to reach out to Pawan & Pooja , or the team at SamagraCS Educational Technology. Keep practicing and happy coding!