C fwrite() Function Tutorial

In this section, we will learn what the fwrite() function is and how it works in C.

Writing to a File in C: C fwrite() Function

In order to write binary data into a file, we can use the fwirte() function.

C fwrite() Function Syntax:

Here’s the prototype of the function:

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

C fwrite() Function Parameters

This function takes 4 arguments:

  1. The first argument is the address of the chunk of data to be written.
  2. The second argument represents the size, in bytes, of the chunks to be written.
  3. The third argument represents the number of chunks to be written.
  4. The last argument identifies the file to be written to.

C fwrite() Function Return Value

The returned value of the function on a successful operation is equal to its third argument, which is the number of chunks. If any other number returned, it means an error happened.

Example: writing to a file in C

#include <stdio.h>
#include <stdlib.h>


int main() {

    char buffer[] = "C programming is cool!";

    FILE *file = fopen("G:/fileOne.txt","w");

    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }


    fwrite(buffer, sizeof(buffer), 1, file);


    fclose(file);

    printf("\nDone\n");
    return 0;
}

Output:

Done

If you open the file, you'll see the binary representation of the content in the `buffer`:

4320 7072 6f67 7261 6d6d 696e 6720 6973

2063 6f6f 6c21 00

Again, this is because the function stores content in binary format.

More to Read:

C fread() function

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies