Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Read/Write structure to a file using C
In C programming, structures can be written to and read from files using the fwrite() and fread() functions. This allows you to store complex data types persistently and retrieve them later.
fwrite() Syntax
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
Parameters:
- ptr − A pointer to the data to be written
- size − Size in bytes of each element
- nmemb − Number of elements to write
- stream − Pointer to the FILE object
fread() Syntax
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Parameters:
- ptr − Pointer to memory block to store data
- size − Size in bytes of each element
- nmemb − Number of elements to read
- stream − Pointer to the FILE object
Example
Here's a complete example showing how to write and read student records to/from a file −
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
int roll_no;
char name[20];
};
int main() {
FILE *file;
// Writing structures to file
file = fopen("students.txt", "wb");
if (file == NULL) {
fprintf(stderr, "Error opening file for writing<br>");
return 1;
}
struct Student student1 = {1, "Ram"};
struct Student student2 = {2, "Shyam"};
fwrite(&student1, sizeof(struct Student), 1, file);
fwrite(&student2, sizeof(struct Student), 1, file);
printf("Student records written to file successfully!<br>");
fclose(file);
// Reading structures from file
file = fopen("students.txt", "rb");
if (file == NULL) {
fprintf(stderr, "Error opening file for reading<br>");
return 1;
}
struct Student student;
printf("\nReading student records from file:<br>");
while (fread(&student, sizeof(struct Student), 1, file)) {
printf("Roll No: %d, Name: %s<br>", student.roll_no, student.name);
}
fclose(file);
return 0;
}
Student records written to file successfully! Reading student records from file: Roll No: 1, Name: Ram Roll No: 2, Name: Shyam
Key Points
- Use "wb" and "rb" modes for binary file operations with structures
- Always check if file opening was successful before proceeding
- The
sizeof(struct Student)ensures correct byte count for each record - Remember to close files after operations
Conclusion
Using fwrite() and fread() with structures provides an efficient way to store and retrieve complex data in C. Always use binary mode and proper error checking for reliable file operations.
Advertisements
