{"id":3605,"date":"2024-03-06T11:37:11","date_gmt":"2024-03-06T11:37:11","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=3605"},"modified":"2024-03-06T11:37:11","modified_gmt":"2024-03-06T11:37:11","slug":"read-write-structure-from-to-a-file-in-c","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/read-write-structure-from-to-a-file-in-c\/","title":{"rendered":"Read\/Write Structure From\/to A File In C"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><h6>Table of Contents<\/h6><nav><ul><li ><a href=\"#read-write-structure-from-to-a-file-in-c\">Read\/Write Structure From\/to A File In C<\/a><\/li><li ><a href=\"#writing-structure-to-a-file-using-fwrite\">Writing Structure to a File using fwrite<\/a><\/li><li ><a href=\"#reading-structure-from-a-file-using-fread\">Reading Structure from a File using fread<\/a><\/li><li ><a href=\"#faq-read-write-structure-from-to-a-file-in-c\">FAQ- Read\/Write Structure From\/to A File In C<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"read-write-structure-from-to-a-file-in-c\">Read\/Write Structure From\/to A File In C<\/h2>\n\n\n\n<p>When it comes to writing to a file in C, handling strings or integers is straightforward using <code>fprintf<\/code> and <code>putc<\/code>. But things can get tricky when dealing with the contents of a struct. That&#8217;s where <code>fwrite<\/code> and <code>fread<\/code> come in handy. They make it simpler to write and read chunks of data, especially when you&#8217;re working with structures. Instead of dealing with individual elements, you can handle the entire block of data more efficiently.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"writing-structure-to-a-file-using-fwrite\">Writing Structure to a File using fwrite<\/h2>\n\n\n\n<p>We can use fwrite() function to write a structure in a file. Hence, fwrite() function will write to the file stream in the form of a binary data block.<\/p>\n\n\n\n<p><strong>Syntax of fwrite()<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)\n<\/code><\/pre>\n\n\n\n<p>Parameters<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>ptr<\/code>: Pointer to the block of memory from which data will be written.<\/li>\n\n\n\n<li><code>size<\/code>: Size of each element to be written, specified in bytes.<\/li>\n\n\n\n<li><code>nmemb<\/code>: Number of elements, each of size <code>size<\/code>, to be written.<\/li>\n\n\n\n<li><code>stream<\/code>: FILE pointer to the output file stream where the data will be written.<\/li>\n<\/ul>\n\n\n\n<p>Return Value<\/p>\n\n\n\n<p>Number of objects that will be written<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program for writing\n\/\/ struct to file\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n \n\/\/ a struct to be read and written\nstruct person {\n    int id;\n    char fname&#91;20];\n    char lname&#91;20];\n};\n \nint main()\n{\n    FILE* outfile;\n \n    \/\/ open file for writing\n    outfile = fopen(\"person.bin\", \"wb\");\n    if (outfile == NULL) {\n        fprintf(stderr, \"\\nError opened file\\n\");\n        exit(1);\n    }\n \n    struct person input1 = { 1, \"rohan\", \"sharma\" };\n \n    \/\/ write struct to file\n    int flag = 0;\n    flag = fwrite(&amp;input1, sizeof(struct person), 1,\n                  outfile);\n    if (flag) {\n        printf(\"Contents of the structure written \"\n               \"successfully\");\n    }\n    else\n        printf(\"Error Writing to File!\");\n \n    \/\/ close file\n    fclose(outfile);\n    return 0;\n}\n <\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Contents of the structure written successfully\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reading-structure-from-a-file-using-fread\">Reading Structure from a File using fread<\/h2>\n\n\n\n<p>We could read structure from a file using fread() function. This function will  read a block of memory from the given stream.<\/p>\n\n\n\n<p>Syntax<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) \n<\/code><\/pre>\n\n\n\n<p>Parameters<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>ptr<\/code>: Pointer to the block of memory where the read data will be stored.<\/li>\n\n\n\n<li><code>size<\/code>: Size of each element to be read, specified in bytes.<\/li>\n\n\n\n<li><code>nmemb<\/code>: Number of elements, each of size <code>size<\/code>, to be read.<\/li>\n\n\n\n<li><code>stream<\/code>: FILE pointer to the input file stream from which data will be read.<\/li>\n<\/ul>\n\n\n\n<p>Return Value<\/p>\n\n\n\n<p>Number of objects that will be written<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program for reading\n\/\/ struct from a file\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n \n\/\/ struct person with 3 fields\nstruct person {\n    int id;\n    char fname&#91;20];\n    char lname&#91;20];\n};\n \n\/\/ Driver program\nint main()\n{\n    FILE* infile;\n \n    \/\/ Open person.dat for reading\n    infile = fopen(\"person1.dat\", \"wb+\");\n    if (infile == NULL) {\n        fprintf(stderr, \"\\nError opening file\\n\");\n        exit(1);\n    }\n \n    struct person write_struct = { 1, \"Rohan\", \"Sharma\" };\n \/\/ writing to file\n    fwrite(&amp;write_struct, sizeof(write_struct), 1, infile);\n \n    struct person read_struct;\n \n    \/\/ setting pointer to start of the file\n    rewind(infile);\n \n    \/\/ reading to read_struct\n    fread(&amp;read_struct, sizeof(read_struct), 1, infile);\n \n    printf(\"Name: %s %s \\nID: %d\", read_struct.fname,\n           read_struct.lname, read_struct.id);\n \n    \/\/ close file\n    fclose(infile);\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Name: Rohan Sharma \nID: 1<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-read-write-structure-from-to-a-file-in-c\">FAQ- Read\/Write Structure From\/to A File In C<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1700224162762\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. How to write and read a structure to a file in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. fwrite() syntax. is  fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) &#8230;<br \/>fread() syntax. fread(void *ptr, size_t size, size_t nmemb, FILE *stream) &#8230;<br \/>Algorithm. Start to  Create a Structure Student to declare variables. &#8230;<br \/>Example Code.<br \/>Ouput. will show Contents to file written successfully !<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1700224171039\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2.What is file structure in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. The <code>FILE<\/code> type in C is a structure, defined in <code>stdio.h<\/code>, representing a file stream. It&#8217;s an opaque data type, so users interact with it using pointers, while the library manages its internal details. The <code>FILE<\/code> structure holds information about the file stream&#8217;s state, allowing consistent file I\/O operations across different systems.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1700224183772\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. How to read from a structure in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. The C function to read a structure is\u00a0<strong>fread()<\/strong>. The format is: fread (* struct, size, count, file);<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Read\/Write Structure From\/to A File In C When it comes to writing to a file in C, handling strings or integers is straightforward using fprintf and putc. But things can get tricky when dealing with the contents of a struct. That&#8217;s where fwrite and fread come in handy. They make it simpler to write and &#8230; <a title=\"Read\/Write Structure From\/to A File In C\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/read-write-structure-from-to-a-file-in-c\/\" aria-label=\"More on Read\/Write Structure From\/to A File In C\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":5432,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[591],"class_list":["post-3605","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-read-write-structure-from-to-a-file-in-c","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3605","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=3605"}],"version-history":[{"count":8,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3605\/revisions"}],"predecessor-version":[{"id":7949,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3605\/revisions\/7949"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/5432"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=3605"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=3605"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=3605"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}