C programming stdio.h function - size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

www.igift‮di‬ea.com

In C programming, the fwrite() function is defined in the stdio.h header file and is used to write data to a file. The function takes four arguments:

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

The first argument ptr is a pointer to the data to be written to the file. The second argument size is the size (in bytes) of each element to be written, and the third argument nmemb is the number of elements to be written.

The last argument stream is a pointer to a FILE object that represents the stream to which the data is to be written.

The fwrite() function returns the total number of elements written to the file. If an error occurs, the function returns a value less than nmemb.

Here's an example of how to use fwrite() to write data to a file:

#include <stdio.h>

int main() {
    FILE *fp;
    char data[] = "Hello, world!";
    size_t size, nmemb, written;

    fp = fopen("example.txt", "w");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    size = sizeof(char);
    nmemb = sizeof(data) / size;
    written = fwrite(data, size, nmemb, fp);
    printf("Wrote %zu elements to the file.\n", written);

    fclose(fp);

    return 0;
}

In the above example, the fwrite() function is used to write the data contained in the data array to the file pointed to by fp. The size of each element is sizeof(char), and the number of elements to be written is determined by dividing the total size of the array (sizeof(data)) by the size of each element.

The number of elements actually written to the file is stored in the written variable and printed to the console.