C File I/O Operations : putw()

The putw() is a integer oriented function. It is similar to the putc(), but it is used to writes integer values from a file. It writes a word ( size of int ) at a time into the output stream. The syntax of putw() is :
 int putw(int number, FILE *fp);
Where number is the integer value needs to be written and fp is a file pointer. On success it returns 0 (zero) , Otherwise, a non-zero value is returned.

C example Code :
#include <stdio.h>

int main() {
  FILE *fp;
  int num;

  // write into file
  fp = fopen("num.txt", "w");
  printf("Enter Some Numbers (Enter 0 to exit) :\n");
  while(num != 0) {
    scanf("%d", &num);
    if(num==0)break;
    putw(num, fp);
  }
  fclose(fp);


  // read from file
  printf("\nContents of the file :\n");
  fp = fopen("num.txt", "r");
  while((num=getw(fp))!= EOF) {
    printf("%d\n", num);
  }

  fclose(fp);
  return 0;
}
Output :

Enter Some Numbers (Enter 0 to exit) :
12345
54321
2018
65536
99999
0

Contents of the file :
12345
54321
2018
65536
99999

Topics :