Read/Write Structure From/to a File in C

For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data.

Writing Structure to a File using fwrite

We can use fwrite() function to easily write a structure in a file. fwrite() function writes the to the file stream in the form of binary data block.

Syntax of fwrite()

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

Parameters

Return Value

Example

C

// C program for writing // struct to file // a struct to be read and written struct person < char fname[20]; char lname[20]; FILE * outfile; // open file for writing outfile = fopen ( "person.bin" , "wb" ); if (outfile == NULL) < fprintf (stderr, "\nError opened file\n" ); struct person input1 = < 1, "rohan" , "sharma" >; // write struct to file int flag = 0; flag = fwrite (&input1, sizeof ( struct person), 1, printf ( "Contents of the structure written " "successfully" ); printf ( "Error Writing to File!" ); // close file fclose (outfile); Output
Contents of the structure written successfully

Reading Structure from a File using fread

We can easily read structure from a file using fread() function. This function reads a block of memory from the given stream.

Syntax of fread()

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

Parameters

Return Value

Example

C

// C program for reading // struct from a file // struct person with 3 fields struct person < char fname[20]; char lname[20]; // Driver program FILE * infile; // Open person.dat for reading infile = fopen ( "person1.dat" , "wb+" ); if (infile == NULL) < fprintf (stderr, "\nError opening file\n" ); struct person write_struct = < 1, "Rohan" , "Sharma" >; // writing to file struct person read_struct; // setting pointer to start of the file rewind (infile); // reading to read_struct printf ( "Name: %s %s \nID: %d" , read_struct.fname, read_struct.lname, read_struct.id); // close file fclose (infile); Output
Name: Rohan Sharma ID: 1

Related Articles:

GeeksforGeeks Like Article -->

Please Login to comment.

Similar Reads

C program to copy contents of one file to another file

[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() < FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) < printf("Cannot open fi

1 min read C | Loops & Control Structure | Question 1

#include <stdio.h> int main() < int i = 1024; for (; i; i >>= 1) printf("GeeksQuiz"); return 0; >How many times will GeeksQuiz be printed in the above program? (A) 10 (B) 11 (C) Infinite (D) The program will show compile-time error Answer: (B) Explanation: In for loop, mentioning expression is optional. >>= is a composi

1 min read C | Loops & Control Structure | Question 2 1 min read C | Loops & Control Structure | Question 3

What is the output of the below program? C/C++ Code #include int main() < int i = 2; switch (i) < case 0: printf("Geeks"); break; case 1: printf("Quiz"); break; default: printf("GeeksQuiz"); >return 0; > (A) Geeks (B) Quiz (C) GeeksQuiz (D) Compile-time error Answer: (C) Explanation: As i=2, so GeeksQuiz is printed. Quiz of this Question Please co

1 min read C | Loops & Control Structure | Question 4

C/C++ Code #include int main() < int i = 3; switch (i) < case 1: printf("Geeks"); break; case 1+2: printf("Quiz"); break; default: printf("GeeksQuiz"); >return 0; > What is the output of the above program? (A) Geeks (B) Quiz (C) GeeksQuiz (D) Compile-time error Answer: (B) Explanation: Expression gets evaluated in cases. The control goes to the se

1 min read C | Loops & Control Structure | Question 5

Predict the output of the below program: C/C++ Code #include #define EVEN 0 #define ODD 1 int main() < int i = 3; switch (i % 2) < case EVEN: printf("Even"); break; case ODD: printf("Odd"); break; default: printf("Default"); >return 0; > (A) Even (B) Odd (C) Default (D) Compile-time error Answer: (B) Explanation: The following C code will print 'o

1 min read C | Loops & Control Structure | Question 6

C/C++ Code #include int main() < int i; if (printf("0")) i = 3; else i = 5; printf("%d", i); return 0; >Predict the output of above program? (A) 3 (B) 5 (C) 03 (D) 05 Answer: (C) Explanation: The control first goes to the if statement where 0 is printed. The printf(\"0\") returns the number of characters being printed i.e. 1. The block under if st

1 min read C | Loops & Control Structure | Question 7

C/C++ Code #include int i; int main() < if (i) < // Do nothing >else < printf("Else"); >return 0; > What is correct about the above program? (A) if block is executed. (B) else block is executed. (C) It is unpredictable as i is not initialized. (D) Error: misplaced else Answer: (B) Explanation: Since i is defined globally, it is initialized with d

1 min read C | Structure & Union | Question 2

Assume that size of an integer is 32 bit. What is the output of following program? #include<stdio.h> struct st < int x; static int y; >; int main() < printf("%d", sizeof(struct st)); return 0; >(A) 4 (B) 8 (C) Compiler Error (D) Runtime Error Answer: (C) Explanation: In C, struct and union types cannot have static members. In C++,

1 min read C | Structure & Union | Question 10

C/C++ Code struct node < int i; float j; >; struct node *s[10]; The above C declaration define \'s\' to be (GATE CS 2000) (A) An array, each element of which is a pointer to a structure of type node (B) A structure of 2 fields, each field being a pointer to an array of 10 elements (C) A structure of 3 fields: an integer, a float, and an array of 10

1 min read C | Structure & Union | Question 4

Consider the following C declaration C/C++ Code struct < short s[5]; union < float y; long z; >u; > t; Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is (GATE CS 2000) (A)22 bytes (B)14 bytes (C)18 bytes (D)10 bytes An

1 min read C | Loops & Control Structure | Question 10

# include <stdio.h> int main() < int i = 0; for (i=0; i<20; i++) < switch(i) < case 0: i += 5; case 1: i += 2; case 5: i += 5; default: i += 4; break; >printf("%d ", i); > return 0; > (A) 5 10 15 20 (B) 7 12 17 22 (C) 16 21 (D) Compiler Error Answer: (C) Explanation: Initially i = 0. Since case 0 is true i becomes 5, and since t

1 min read C | Loops & Control Structure | Question 11

Output of following C program? #include<stdio.h> int main() < int i = 0; for (printf("1st\n"); i < 2 && printf("2nd\n"); ++i && printf("3rd\n")) < printf("*\n"); >return 0; > (A) 1st 2nd * 3rd 2nd * (B) 1st 2nd * 3rd 2nd * 3rd (C) 1st 2nd 3rd * 2nd 3rd (D) 1st 2nd 3rd * 1st 2nd 3rd A

1 min read C | Loops & Control Structure | Question 12

#include <stdio.h> int main() < int i; for (i = 1; i != 10; i += 2) printf(" GeeksQuiz "); return 0; >(A) GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz (B) GeeksQuiz GeeksQuiz GeeksQuiz . infinite times (C) GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz (D) GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz Answer: (B) Exp

1 min read C | Loops & Control Structure | Question 13

What will be the output of the following C program segment? (GATE CS 2012) char inchar = 'A'; switch (inchar) < case 'A' : printf ("choice A \n") ; case 'B' : printf ("choice B ") ; case 'C' : case 'D' : case 'E' : default: printf ("No Choice") ; >(A) No choice (B) Choice A (C) Choice A Choice B No choice (D) Program

1 min read C | Loops & Control Structure | Question 15

In the following program, X represents the Data Type of the variable check. #include <stdio.h> int main() < X check; switch (check) < // Some case labels >return 0; > Which of the following cannot represent X? (A) int (B) char (C) enum (D) float Answer: (D) Explanation: A switch expression can be int, char and enum. A float variable/expressi

1 min read C | Loops & Control Structure | Question 16

What is the output of the following program? #include <stdio.h> int main() < char check = 'a'; switch (check) < case 'a' || 1: printf("Geeks "); case 'b' || 2: printf("Quiz "); break; default: printf("GeeksQuiz"); >return 0; > (A) Geeks (B) Geeks Quiz (C) Geeks Quiz GeeksQuiz (D) Compile-time error Answer: (D) E

1 min read C | Loops & Control Structure | Question 17 1 min read C | Structure & Union | Question 7

union test < int x; char arr[8]; int y; >; int main() < printf("%d", sizeof(union test)); return 0; >Predict the output of above program. Assume that the size of an integer is 4 bytes and size of character is 1 byte. Also assume that there is no alignment needed. (A) 12 (B) 16 (C) 8 (D) Compiler Error Answer: (C) Explanation: When we dec

1 min read C | Structure & Union | Question 8

union test < int x; char arr[4]; int y; >; int main() < union test t; t.x = 0; t.arr[1] = 'G'; printf("%s", t.arr); return 0; >Predict the output of above program. Assume that the size of an integer is 4 bytes and size of character is 1 byte. Also assume that there is no alignment needed. (A) Nothing is printed (B) G (C) Garbage characte

1 min read C | Structure & Union | Question 9

# include <iostream> # include <string.h> using namespace std; struct Test < char str[20]; >; int main() < struct Test st1, st2; strcpy(st1.str, "GeeksQuiz"); st2 = st1; st1.str[0] = 'S'; cout << st2.str; return 0; >(A) Segmentation Fault (B) SeeksQuiz (C) GeeksQuiz (D) Compiler Error Answer: (C) Explanation: Array memb

1 min read C | Loops & Control Structure | Question 18

How many times GeeksQuiz is printed #include<stdio.h> int main() < int i = -5; while (i <= 5) < if (i >= 0) break; else < i++; continue; >printf("GeeksQuiz"); > return 0; > (A) 10 times (B) 5 times (C) Infinite times (D) 0 times Answer: (D) Explanation: The loop keeps incrementing i while it is smaller than 0. When i becomes

1 min read C | Loops & Control Structure | Question 19

#include <stdio.h> int main() < int i = 3; while (i--) < int i = 100; i--; printf("%d ", i); >return 0; > (A) Infinite Loop (B) 99 99 99 (C) 99 98 97 (D) 2 2 2 Answer: (B) Explanation: Note that the i–- in the statement while(i-–) changes the i of main() And i== just after declaration statement int i=100; changes local i of while l

1 min read C | Loops & Control Structure | Question 20

#include <stdio.h> int main() < int x = 3; if (x == 2); x = 0; if (x == 3) x++; else x += 2; printf("x = %d", x); return 0; >(A) x = 4 (B) x = 2 (C) Compiler Error (D) x = 0 Answer: (B) Explanation: Value of x would be 2. Note the semicolon after first if statement. x becomes 0 after the first if statement. So control goes to else

1 min read C | Loops & Control Structure | Question 21

#include&lt;stdio.h&gt; int main() < int a = 5; switch(a) < default: a = 4; case 6: a--; case 5: a = a+1; case 1: a = a-1; >printf(&quot;%d \n&quot;, a); return 0; > (A) 3 (B) 4 (C) 5 (D) None of these Answer: (C) Explanation: There is no break statement, so first a = a + 1 is executed, then a = a-1 is executed. Quiz of this Questi

1 min read C | Structure & Union | Question 10

Predict the output of following C program #include<stdio.h> struct Point < int x, y, z; >; int main() < struct Point p1 = <.y = 0, .z = 1, .x = 2>; printf("%d %d %d", p1.x, p1.y, p1.z); return 0; > (A) Compiler Error (B) 2 0 1 (C) 0 1 2 (D) 2 1 0 Answer: (B) Explanation: Refer designated Initialization discussed here.Quiz of this Qu

1 min read Difference between Structure and Array in C

Array in C An array is collection of items stored at contiguous memory locations. Structure in C A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. Difference between Structure and Array ARRAYSTRUCTUREArray refers to a collection consistin

2 min read Structure of the C Program

The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. C program must follow the below-mentioned outline in order to successfully compile and execute. Debugging is easier in a well-structured C program. Sections of the C Program There are 6 basic sections resp

5 min read Structure Pointer in C

A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure known as the structure pointer. Complex data structures like Linked lists, trees, graphs, etc. are created with the help of structure pointers. The structure pointer tells the address of a structure in memory by pointing the variabl

3 min read Why does empty Structure has size 1 byte in C++ but 0 byte in C

A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. The general syntax for creating a structure is as shown below: Syntax- struct structureName< member1; member2; member3; . . . memberN; >