C File I/O Operations : getw()

The getw() is a integer oriented function. It is similar to the getc(), but it is used to read integer values from a file. It reads a word ( size of int ) at a time from the input stream. The syntax of getw() is :
 int getw(FILE *fp);
Where fp is file pointer. On success it returns the integer value and if the stream is at end-of-file, then it will return EOF, and also on any error situation it returns EOF.

C example Code :
#include <stdio.h>

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

  // write into file
  fp = fopen("num.txt", "w");
  num = 12345;
  putw(num, fp);
  num = 2018;
  putw(num, fp);
  num = 9999;
  putw(num, fp);

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

  return 0;
Output :


The above code write 3 numbers into a file num.txt and then reads its contents and print the output.

Topics :