Read/Write structure to a file in C

2.5


Prerequisite: Structure in C

For writing in 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 struct. fwrite and fread make task easier when you want to write and read blocks of data.

  1. fwrite : Following is the declaration of fwrite function
    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
    ptr - This is pointer to array of elements to be written
    size -  This is the size in bytes of each element to be written
    nmemb - This is the number of elements, each one with a size of size bytes
    stream - This is the pointer to a FILE object that specifies an output stream
    
    // C program for writing 
    // struct to file
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // a struct to read and write
    struct person 
    {
        int id;
        char fname[20];
        char lname[20];
    };
    
    int main ()
    {
        FILE *outfile;
        
        // open file for writing
        outfile = fopen ("person.dat", "w");
        if (outfile == NULL)
        {
        	fprintf(stderr, "\nError opend file\n");
        	exit (1);
        }
    
        struct person input1 = {1, "rohan", "sharma"};
        struct person input2 = {2, "mahendra", "dhoni"};
        
        // write struct to file
        fwrite (&input1, sizeof(struct person), 1, outfile);
        fwrite (&input2, sizeof(struct person), 1, outfile);
        
        if(fwrite != 0) 
            printf("contents to file written successfully !\n");
        else 
            printf("error writing file !\n");
        return 0;
    }
    

    Output:

    gcc demowrite.c
    ./a.out
    contents to file written successfully!
    
  2. fread : Following is the declaration of fread function
    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
    ptr - This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
    size - This is the size in bytes of each element to be read.
    nmemb - This is the number of elements, each one with a size of size bytes.
    stream - This is the pointer to a FILE object that specifies an input stream.
    // C program for reading 
    // struct from a file
    #include <stdio.h>
    #include <stdlib.h>
    
    // struct person with 3 fields
    struct person 
    {
        int id;
        char fname[20];
        char lname[20];
    };
    
    // Driver program
    int main ()
    {
        FILE *infile;
        struct person input;
        
        // Open person.dat for reading
        infile = fopen ("person.dat", "r");
        if (infile == NULL)
        {
        	fprintf(stderr, "\nError opening file\n");
        	exit (1);
        }
        
        // read file contents till end of file
        while(fread(&input, sizeof(struct person), 1, infile))
        	printf ("id = %d name = %s %s\n", input.id,
        	input.fname, input.lname);
        return 0;
    }
    

    Output:

    gcc demoread.c
    ./a.out
    id = 1   name = rohan sharma
    id = 2   name = mahendra dhoni
    

This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.5 Average Difficulty : 2.5/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.