How to Read a Struct from a Binary File in C? - GeeksforGeeks (2024)

Skip to content

How to Read a Struct from a Binary File in C? - GeeksforGeeks (1)

Last Updated : 22 Feb, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

The structure in C allows the users to create user-defined data types that can be used to group data items of different types into a single unit. We can save this structure in a file using C file handling. In this article, we will learn how we can read a struct from a binary file in C.

Read a Struct from a Binary File in C

To read a struct from a binary file in C, we will first have to open the binary file using the fopen() method in rb mode. Then we will use the fread() function to read the structure from the file.

Syntax of fread()

size_t fread(void * buffer, size_t size, size_t count, FILE * stream);

here,

  • buffer:It refers to the pointer to the buffer memory block where the data read will be stored.
  • size:It refers to the size of each element in bytes.
  • count:It refers to the count of elements to be read.
  • stream:It refers to the pointer to the file stream.

C Program to Read a Struct from a Binary File

C

// C program to read a struct from a binary file

#include <stdio.h>

typedef struct {

int id;

char name[50];

float salary;

} Employee;

int main()

{

// open the file in rb mode

FILE* file = fopen("employee_data.bin", "rb");

// check if the file was successfully opened

if (file == NULL) {

perror("Error opening file");

return 1;

}

// Define the struct

Employee employee;

// Read the structs present in the file

while (fread(&employee, sizeof(Employee), 1, file)

== 1) {

// Process the read data (e.g., print or manipulate)

printf("Employee ID: %d, Name: %s, Salary: %.2f\n",

employee.id, employee.name, employee.salary);

}

// close the file

fclose(file);

return 0;

}

Output

Employee ID: 1, Name: John Doe, Salary: 50000.0
Employee ID: 2, Name: Jane Smith, Salary: 60000.0

Time Complexity: O(N) where N is the number of structs in the file
Auxiliary Space: O(1)



Please Login to comment...

Similar Reads

How to Declare a Struct Inside a Struct in C?

A structure is a composite data type in C programming that enables combining several data types under one name. A structure inside a structure is also called a nested structure. In this article, we will learn how to declare a structure inside a structure in C++. Declare a Struct Inside a Struct in CTo declare a structure inside a structure, we need

2 min read

How to Write a Struct to a Binary File in C?

C file handling allows users to store the data from a C program to a file in either the text or the binary format. In this article, we will learn how to write a struct to a binary file in C. Writing Structure into a Binary File in CTo write a struct to a binary file, we can use the fwrite() function that writes the given bytes of data in the file i

2 min read

Is sizeof for a struct equal to the sum of sizeof of each member?

Prerequisite : sizeof operator in C The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure. Different compilers m

3 min read

Difference between Struct and Enum in C/C++ with Examples

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. The ‘struct’ keyword is used to create a structure. Syntax: struct structureName{ member1; member2; member3; . . . memberN; }; Below is the implementation: C/C++ Code #inc

3 min read

Operations on struct variables in C

In C, the only operation that can be applied to struct variables is assignment. Any other operation (e.g. equality check) is not allowed on struct variables. For example, program 1 works without any error and program 2 fails in compilation. Program 1 #include &lt;stdio.h&gt; struct Point { int x; int y; }; int main() { struct Point p1 = {10, 20}; s

1 min read

Struct Hack

What will be the size of following structure? C/C++ Code struct employee { int emp_id; int name_len; char name[0]; }; 4 + 4 + 0 = 8 bytes.And what about size of "name[0]". In gcc, when we create an array of zero length, it is considered as array of incomplete type that's why gcc reports its size as "0" bytes. This technique is known as "Struct Hack

3 min read

Conversion of Struct data type to Hex String and vice versa

Most of the log files produced in system are either in binary(0,1) or hex(0x) formats. Sometimes you might need to map this data into readable format. Conversion of this hex information into system defined data types such as 'int/string/float' is comparatively easy. On the other hand when you have some user defined data types such as 'struct' the p

2 min read

How to Declare a Pointer to a Struct in C?

Structure (or structs) in the C programming language provides a way to combine variables of several data types under one name and pointers provide a means of storing memory addresses. In this article, we will learn how to declare such a pointer to a struct in C. Declaration of Pointer to Struct in CTo declare a pointer to a struct we can use the st

2 min read

How to Modify Struct Members Using a Pointer in C?

In C++, we use structure to group multiple different types of variables inside a single type. These different variables are called the members of structures. In this article, we will discuss how to modify the struct member using a pointer in C. Example Input: myStruct.mem1 = 10; myStruct.mem2 = 'a'; Output: myStruct.mem1 = 28; myStruct.mem2 = 'z';

1 min read

How to Initialize Char Array in Struct in C?

In C++, we can also define a character array as a member of a structure for storing strings. In this article, we will discuss how to initialize a char array in a struct in C. Initialization of Char Array in Struct in CWhen we create a structure instance (variable) in C that includes a char array, we can set an initial value for that char array dire

2 min read

How to Declare a Struct Member Inside a Union in C?

A union contains different types of variables as its members and all these members share a memory location. In this article, we will learn how to declare and access the struct member inside a union in C++. Structure Inside Union in CTo declare a structure inside a union we can use the below syntax: Syntax to Declare Structure Inside Union in Cunion

2 min read

How to use typedef for a Struct in C?

In C, we use typedef to create aliases for already existing types. For structure, we can define a new name that can be used in place of the original struct name. In this article, we will learn how to create a typedef for a structure in C++. Use the typedef struct in CTo create an alias for a structure in C, we can use the typedef keyword typedef fo

2 min read

How to Search in Array of Struct in C?

In C, a struct (short for structure) is a user-defined data type that allows us to combine data items of different kinds. An array of structs is an array in which each element is of struct type. In this article, we will learn how to search for a specific element in an array of structs. Example: Input:Person people[3] = { { "Alice", 25 }, { "Bob", 3

2 min read

How to Pack a Struct in C?

In C, when you declare a structure, the compiler allocates memory for its members, and the way it does this can involve adding padding between members for alignment purposes. struct packing refers to the arrangement of the members of a structure in memory so that there is no extra space left. In this article, we are going to learn how to pack a str

1 min read

How to Use bsearch with an Array of Struct in C?

The bsearch function in C is a standard library function defined in the stdlib.h header file that is used to perform binary search on array-like structure. In this article, we will learn to use bsearch with an array of struct in C. Input: struct Person people[] = { { 1, "Ram" }, { 2, "Rohan" }, { 4, "Ria" }, { 3, "Mohan" } }; Key: 3 Output: Person

3 min read

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

3 min read

C program to read a range of bytes from file and print it to console

Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console. Functions Used: fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.fgetc(): Reading the characters from the file.fclose(): For closing a file. Approach: Initialize a file pointer,

2 min read

C Program to Read and Print All Files From a Zip File

To understand how to write a C program for reading and printing zip files, it's important to know what exactly a zip file is. At its core, a zip file contains one or more files compressed using specific compression algorithms.Including the compressed data of the files, the zip file contains meta and header information about all files inside the zip

6 min read

cJSON - JSON File Write/Read/Modify in C

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using

6 min read

Implement your own tail (Read last n lines of a huge file)

Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi

4 min read

lseek() in C/C++ to read the alternate nth byte and write it in another file

From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild

2 min read

How to Read From a File in C?

File handing in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. In this article, we will explore how to read from a file in C usin

2 min read

How to Read a File Line by Line in C?

In C, reading a file line by line is a process that involves opening the file, reading its contents line by line until the end of the file is reached, processing each line as needed, and then closing the file. In this article, we will learn how to read a file line by line in C. Reading a File Line by Line in CIn C, the fgets() function is a standar

2 min read

C Program to Read Content of a File

In C, reading the contents of a file involves opening the file, reading its data, and then processing or displaying the data. Example Input: File containing "This is a test file.\nIt has multiple lines." Output: This is a test file.It has multiple lines. Explanation: The program reads and displays the multiline text from the file. In this article,

8 min read

C program to check whether the file is JPEG file or not

Write a C program which inputs a file as a command-line arguments and detects whether the file is JPEG(Joint Photographic Experts Group) or not. Approach: We will give an image as a command line argument while executing the code. Read the first three bytes of the given image(file). After reading the file bytes, compare it with the condition for JPE

2 min read

C program to copy contents of one file to another file

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

1 min read

How to read a PGMB format image in C

PGM or Portable Gray Map file is a grayscale image where each pixel is encoded with 1 or 2 bytes. It contains header information and pixel grayscale values in a matrix form. Approach: The idea is followed to read PGMB format image is as follows: Open a PGMB (binary format PGM image).Extract the pixel information, which can be then used for further

5 min read

How to input or read a Character, Word and a Sentence from user in C?

C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating system

4 min read

Input-output system calls in C | Create, Open, Close, Read, Write

System calls are the calls that a program makes to the system kernel to provide the services to which the program does not have direct access. For example, providing access to input and output devices such as monitors and keyboards. We can use various functions provided in the C Programming language for input/output system calls such as create, ope

10 min read

How to Read Data Using sscanf() in C?

In C, sscanf() function stands for "String Scan Formatted". This function is used for parsing the formatted strings, unlike scanf() that reads from the input stream, the sscanf() function extracts data from a string. In this article, we will learn how to read data using sscanf() function in C. Example: Input: char *str = "Ram Manager 30";Output:Nam

2 min read

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

How to Read a Struct from a Binary File in C? - GeeksforGeeks (4)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

Continue without supporting 😢

`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }
How to Read a Struct from a Binary File in C? - GeeksforGeeks (2024)
Top Articles
Upload a file to IPFS
Fake HMRC letters - How to spot them and what to do - Maynard Johns
9.4: Resonance Lewis Structures
Lowe's Garden Fence Roll
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
Forozdz
O'reilly's Auto Parts Closest To My Location
Directions To Franklin Mills Mall
Rondale Moore Or Gabe Davis
Nation Hearing Near Me
About Goodwill – Goodwill NY/NJ
Amateur Lesbian Spanking
Lantana Blocc Compton Crips
Es.cvs.com/Otchs/Devoted
W303 Tarkov
Items/Tm/Hm cheats for Pokemon FireRed on GBA
How Many Slices Are In A Large Pizza? | Number Of Pizzas To Order For Your Next Party
How to find cash from balance sheet?
How Much Are Tb Tests At Cvs
24 Best Things To Do in Great Yarmouth Norfolk
Simpsons Tapped Out Road To Riches
Best Uf Sororities
Ibukunore
Vrachtwagens in Nederland kopen - gebruikt en nieuw - TrucksNL
Pinellas Fire Active Calls
Walgreens Alma School And Dynamite
Jeff Now Phone Number
Jenna Ortega’s Height, Age, Net Worth & Biography
Touchless Car Wash Schaumburg
1973 Coupe Comparo: HQ GTS 350 + XA Falcon GT + VH Charger E55 + Leyland Force 7V
Jeff Nippard Push Pull Program Pdf
Best Middle Schools In Queens Ny
Radical Red Ability Pill
Wbap Iheart
Miller Plonka Obituaries
Isablove
Current Time In Maryland
A Grade Ahead Reviews the Book vs. The Movie: Cloudy with a Chance of Meatballs - A Grade Ahead Blog
Egg Crutch Glove Envelope
Wlds Obits
Final Fantasy 7 Remake Nexus
Wrigley Rooftops Promo Code
Craigs List Palm Springs
Shane Gillis’s Fall and Rise
Henry Ford’s Greatest Achievements and Inventions - World History Edu
Wal-Mart 140 Supercenter Products
Tattoo Shops In Ocean City Nj
Memberweb Bw
FedEx Authorized ShipCenter - Edouard Pack And Ship at Cape Coral, FL - 2301 Del Prado Blvd Ste 690 33990
Gabrielle Abbate Obituary
Unit 11 Homework 3 Area Of Composite Figures
Benjamin Franklin - Printer, Junto, Experiments on Electricity
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6287

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.