🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The fread() function is used for reading binary data from files. It reads a specified number of elements of a specified size from a given stream into a block of memory.
fread() Function Syntax
The syntax for the fread() function is as follows:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Parameters:
ptr: A pointer to a block of memory where the read data will be stored.size: The size in bytes of each element to be read.nmemb: The number of elements, each one with a size ofsizebytes.stream: A pointer to aFILEobject that specifies an input stream.
Returns:
- The function returns the total number of elements successfully read, which may be less than
nmembif an error or end-of-file condition occurs.
Understanding fread()
The fread() function reads data from the specified stream and stores it in the block of memory pointed to by ptr. It reads up to nmemb elements, each of size bytes. The function stops reading when it has read nmemb elements, or if an error or end-of-file condition is encountered.
Examples
Reading an Array of Integers
To demonstrate how to use fread() to read an array of integers from a binary file, we will write a simple program.
Example
#include <stdio.h>
int main() {
FILE *file;
int numbers[5];
// Open the file for reading
file = fopen("numbers.bin", "rb");
if (file == NULL) {
printf("Error: Could not open file for reading.\n");
return 1;
}
// Read data from the file into the array
size_t elementsRead = fread(numbers, sizeof(int), 5, file);
if (elementsRead != 5) {
printf("Error: Could not read the correct number of elements.\n");
fclose(file);
return 1;
}
// Close the file
fclose(file);
// Print the read data
for (int i = 0; i < 5; i++) {
printf("Number %d: %d\n", i + 1, numbers[i]);
}
return 0;
}
Output (assuming numbers.bin contains five integers):
Number 1: 10
Number 2: 20
Number 3: 30
Number 4: 40
Number 5: 50
Reading a Structure from a Binary File
This example demonstrates how to use fread() to read a structure from a binary file.
Example
#include <stdio.h>
typedef struct {
char name[50];
int age;
float salary;
} Employee;
int main() {
FILE *file;
Employee emp;
// Open the file for reading
file = fopen("employee.bin", "rb");
if (file == NULL) {
printf("Error: Could not open file for reading.\n");
return 1;
}
// Read data from the file into the structure
size_t elementsRead = fread(&emp, sizeof(Employee), 1, file);
if (elementsRead != 1) {
printf("Error: Could not read the correct number of elements.\n");
fclose(file);
return 1;
}
// Close the file
fclose(file);
// Print the read data
printf("Name: %s\n", emp.name);
printf("Age: %d\n", emp.age);
printf("Salary: %.2f\n", emp.salary);
return 0;
}
Output (assuming employee.bin contains one Employee structure):
Name: Ramesh Fadatare
Age: 30
Salary: 60000.00
Real-World Use Case
Reading Configuration Data
In real-world applications, the fread() function can be used to read configuration data from a binary file into memory.
Example
#include <stdio.h>
typedef struct {
char url[100];
int timeout;
int maxConnections;
} Config;
int main() {
FILE *file;
Config config;
// Open the file for reading
file = fopen("config.bin", "rb");
if (file == NULL) {
printf("Error: Could not open file for reading.\n");
return 1;
}
// Read data from the file into the configuration structure
size_t elementsRead = fread(&config, sizeof(Config), 1, file);
if (elementsRead != 1) {
printf("Error: Could not read the correct number of elements.\n");
fclose(file);
return 1;
}
// Close the file
fclose(file);
// Print the read data
printf("URL: %s\n", config.url);
printf("Timeout: %d\n", config.timeout);
printf("Max Connections: %d\n", config.maxConnections);
return 0;
}
Output (assuming config.bin contains one Config structure):
URL: http://example.com
Timeout: 5000
Max Connections: 100
Conclusion
The fread() function in C is a standard library function that reads data from a given stream into an array. It is part of the C standard library (stdio.h) and is commonly used for binary file input operations.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment