C fwrite() function

C library function - fwrite()

The fwrite() function is used to write up to count items, each of size bytes in length, from buffer to the output stream.


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

fwrite() Parameters:

Name Description Required /Optional
buffer A pointer to the data (to write out) or empty buffer (to read into). Required
size The size (number of bytes) of each element of data. Required
count The number of elements. Required
stream The opened (via fopen) stream. Required

Return value from fwrite()

  • Returns the number of full items successfully written, which can be fewer than count if an error occurs.
  • When using fwrite() for record output, set size to 1 and count to the length of the record to obtain the number of bytes written. You can only write one record at a time when using record I/O.

Example: fwrite() function

Following example write and read a specified string:

int main () {
   FILE *fp;
   char str[] = "C programming tutorial.";
   fp = fopen( "test.txt" , "w" );
   fwrite(str , 1 , sizeof(str) , fp );

   fp = fopen("test.txt","r");
   int c;
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      printf("%c", c);


C programming tutorial.

Errors: The value of errno can be set to:

Value Meaning
ECONVERT A pointer to the data (to write out) or empty buffer (to read into).
ENOTWRITE The file is not open for write operations.
EPAD Padding occurred on a write operation.
EPUTANDGET An illegal write operation occurred after a read operation.
ESTDERR stderr cannot be opened.
ESTDIN stdin cannot be opened.
ESTDOUT stdout cannot be opened.
ETRUNC Truncation occurred on I/O operation.
EIOERROR A non-recoverable I/O error occurred.
EIORECERR A recoverable I/O error occurred.

C Programming Code Editor:

Previous C Programming: C ftell()
Next C Programming: C remove()

Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M