
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read and Write Structure to a File Using C
fwrite() and fread() is used to write to a file in C.
fwrite() syntax
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
where
ptr - A pointer to array of elements to be written
size - Size in bytes of each element to be written
nmemb - Number of elements, each one with a size of bytes
stream – A pointer to a FILE object that specifies an output stream
fread() syntax
fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
where
ptr - A pointer to a block of memory with a minimum size of size*nmemb bytes.
size - Size in bytes of each element to be read.
nmemb - Number of elements, each one with a size of bytes.
stream - A pointer to a FILE object that specifies an input stream.
Algorithm
Begin Create a structure Student to declare variables. Open file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write struct using write method. Close the file for writing. Open the file to read. Check if any error occurs in file opening. If file open successfully, read the file using read method. Close the file for reading. Check if any error occurs. Print the data. End.
This is an example to read/write structure in C:
Example Code
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Student { int roll_no; char name[20]; }; int main () { FILE *of; of= fopen ("c1.txt", "w"); if (of == NULL) { fprintf(stderr, "
Error to open the file
"); exit (1); } struct Student inp1 = {1, "Ram"}; struct Student inp2 = {2, "Shyam"}; fwrite (&inp1, sizeof(struct Student), 1, of); fwrite (&inp2, sizeof(struct Student), 1, of); if(fwrite != 0) printf("Contents to file written successfully !
"); else printf("Error writing file !
"); fclose (of); FILE *inf; struct Student inp; inf = fopen ("c1.txt", "r"); if (inf == NULL) { fprintf(stderr, "
Error to open the file
"); exit (1); } while(fread(&inp, sizeof(struct Student), 1, inf)) printf ("roll_no = %d name = %s
", inp.roll_no, inp.name); fclose (inf); }
Ouput
Contents to file written successfully ! roll_no = 1 name = Ram roll_no = 2 name = Shyam
Advertisements