Integer Input and Output

Integer I/O includes getw(), putw() functions. Those functions we are going to discuss in this blog.

putw()

This function is used to write any integer into a file. After writing any integer (or reading), the pointer will point to the next location. The syntax is written below.

putw(<integer that we want to pass>,<file pointer name>);

Suppose we want to make file pointer fp1 to point to a text file having the name f1.txt. and we want to write 10 into file f1.txt then below is an example of putw syntax.

Ex.

putw(10,fp1);

getw()

This function is used to read an integer from a file. This will read an integer from the file from that location, which file pointer is pointing. Suppose the file pointer is pointing to location 4 then getw will read the integer which is written at location 4. If we want to read data from the starting of a file then we have to make a pointer to point at the starting of the file. (For that we can use the rewind function. rewind(<file pointer name>) )

<character variable> = getw(<file pointer name>);

If we use the same previous example then below is the syntax for getw. And i is an integer variable. After using the below syntax if we print the value of i then it will print an integer from the location which is pointed by file pointer fp1.

Ex. 

i = getw(fp1);

Example program structure to understand the use putw and getw

In the below example, f1 is the file name and fp1 is the file pointer. First, we have used fopen with mode w+ because we want to write using putw and read using getw. Then we have used putw to write integer 10 in the f1 file. Now pointer fp1 is pointing to the location after 10 because it has already written 10 at that location so now it is pointing to the location after 10.
But if we want to read 10 then the pointer should point to the location where 10 is written so we are using the rewind function to set the pointer at the beginning of the file. Now we are using putw to print a character at the beginning which is 10.

#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp1;
  int i;
  clrscr();
  fp1=fopen("f1.txt","w+");
  putw(10,fp1);
  rewind(fp1);
  i=getw(fp1);
  printf("integer = %d ",i);
  fclose(fp1);
  getch(); 
}

Output:

Learning from this blog:

  1. Use of putw and getw.
  2. The syntax for putw.
  3. What is the use of the rewind function?
  4. Syntax of getw.
  5. Write a program using putw and getw.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments