C - File Handling - Read and Write Integers

C Programming


In this tutorial we will learn to read and write integer numbers in files in C programming language.

We have already learned how to read and write characters in files in C in the previous tutorial. In this tutorial we will cover the getw() and putw() function to read and write integers in files.

The getw and putw I/O functions

We use the getw() and putw() I/O functions to read an integer from a file and write an integer to a file respectively.

Syntax of getw:

int num = getw(fptr);

Where, fptr is a file pointer.

Syntax of putw:

putw(n, fptr);

Where, n is the integer we want to write in a file and fptr is a file pointer.

Write a program in C to create a new file and save integer numbers entered by user in a file

For this we will first create a FILE pointer and create a file by the name integers. You can use any other name you like.

Then we will use the putw() function to write the integer number in the file. When -1 is entered we terminate the reading and close the file.

After that we can use the getw() function to read the file data till we hit the EOF (End Of File) character and show it in the console.

#include <stdio.h>

int main(void) {
  // creating a FILE variable
  FILE *fptr;
  // integer variable
  int num;
  // open the file in write mode
  fptr = fopen("integers", "w");
  if (fptr != NULL) {
    printf("File created successfully!\n");
  else {
    printf("Failed to create the file.\n");
    // exit status for OS that an error occurred
    return -1;
  // enter integer numbers
  printf("Enter some integer numbers [Enter -1 to exit]: ");
  while (1) {
    scanf("%d", &num);
    if (num != -1) {
      putw(num, fptr);
    else {
  // close connection
  // open file for reading
  fptr = fopen("integers", "r");
  // display numbers
  while ( (num = getw(fptr)) != EOF ) {
    printf("%d\n", num);
  printf("\nEnd of file.\n");
  // close connection
  return 0;


File created successfully!
Enter some integer numbers [Enter -1 to exit]: 10 20 30 40 50 -1


End of file.

Following is the content inside the integers file.