Read/Write structure to a file in C
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.
- 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
gcc demowrite.c ./a.out contents to file written successfully!
- 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.
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 write.geeksforgeeks.org or mail your article to email@example.com. 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.