C Programming/stdio.h/fwrite

The fread and fwrite functions respectively provide the file operations of input and output. fread and fwrite are declared in <stdio.h>. It usually wraps write.

Writing a file using fwrite

edit

fwrite is defined as

int fwrite ( const void * array, size_t size, size_t count, FILE * stream );

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

The function will return the number of elements written successfully. The return value will be equal to count if the write completes successfully. In case of a write error, the return value will be less than count.

Example

edit

The following program opens a file named sample.txt, writes an array of characters to the file, and closes it.

 #include <stdio.h>
 #include <stdlib.h>
 int main(void)
 {
     FILE *file_ptr;
     int iCount;
     char arr[6] = "hello";
 
     file_ptr = fopen("sample.txt", "wb");
     iCount = fwrite(arr, 1, 5, file_ptr);
     fclose(file_ptr);
 
     return 0;
 }