Use C fwrite function to objects to a file

Syntax

C fwrite function has the following syntax.

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

C fwrite function is from header file stdio.h.

Description

C fwrite function writes count number of objects and returns the number of items written on success. Fewer items written means failure.

Example

Write objects to a file using C fwrite function.


#include <stdio.h>
#include <stdlib.h>
/* w  w w. ja v  a 2s. c  om*/
int main(void)
{
  FILE *fp;
  float f=12.23;

  if((fp=fopen("test", "wb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  fwrite(&f, sizeof(float), 1, fp);

  fclose(fp);

  return 0;
}

Example 2


#include <stdio.h>
//from w w  w  . j a  va  2s .co m
int main ()
{
  FILE *file;
  char str[] = "This buffer contains 34 characters";
  file = fopen ("my.txt" , "w");
  fwrite (str , 1 , 34 , file);
  fclose (file);
  return 0;
}




















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h