Fwrite

From Wikipedia, the free encyclopedia

The correct title of this article is fwrite. The initial letter is shown capitalized due to technical restrictions.

In the C programming language, the fread and fwrite functions respectively provide the file operations of input and output. fread and fwrite are declared in <stdio.h>.

[edit] Writing a file using fwrite

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. It will write up to 'count' items each of size specified by 'size'. The postion indicator of the stream will be advanced by the amount of bytes written successfully.

The function will return the number of bytes 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.

[edit] Example

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

#include <stdio.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;
}