fwrite in c: The function size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream); writes an array pointed by ptr of count elements, where each element is of size bytes, to the current position in the stream. It will advance the position indicator of the stream by the total number of bytes written in file(size*count bytes).
Function prototype of fwrite
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
- ptr : This is a pointer to an array, whose content to be written on file.
- size : This is the size of each element in bytes.
- count : This is the number of elements of size bytes to be written.
- stream : A pointer to a FILE object which identifies a stream.
Return value of fwrite
fwrite c example: This function returns the total number of elements successfully written. If the number of elements written is not same as count then the error indicator (ferror) will be set for the stream.
C program using fwrite function
The following program shows the use of fwrite function to write a character array on a file. In below program, we first write a string in file using fwrite function then we rewind the file position indicator and prints the content of file, which was earlier written by fwrite function.
#include <stdio.h> #include <string.h> int main (){ FILE *file; char *str = "fwrite C Standard Library function"; int ch; file = fopen("textFile.txt" , "w+"); /* writing a string in file */ fwrite(str, strlen(str), sizeof(char), file); /* rewind position indicator to the beginning of the file */ rewind(file); /* Print content of file */ while(!feof(file)){ ch = fgetc(file); printf("%c", ch); } fclose(file); return(0); }
Output
fwrite C Standard Library function