w3resource

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.

Syntax:

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:

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

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

Output:

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()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

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