/    /  Reading and Printing integers from file

Reading and Printing integers from file

 

Reading and Printing only integer value:getw() and putw()

 

The getw( ) and putw( ) are predefined file handling integer-oriented functions. These are similar to getc( ) and putc( ) and serve to read and write integer values. These functions would be helpful when we only handle integer data. The general forms of getw and putw are:

 

Syntax for getw( ):

 

integervariable=getw(filepointer);

 

Example:

 

int n;
n= getw(fp);

 

Syntax for putw( ):

 

putw(integervariable, filepointer);

 

Example:

 

putw(n,fp);

 

Example program:

 

To Write and Read only one Integer Value in a file.

 

#include<stdio.h>
main()
{ intn,m;
FILE *fp=fopen("num.txt","w");
puts("Enter a number:");
scanf("%d",&n);
putw(n,fp); /* printing only integer value in a file */
fclose(fp);
fp=fopen("num.txt","r");
m=getw(fp); /* reading only integer value from a file */
printf("From File int val=%d",m);
}

 

Output1:

 

Reading and Printing integers from file

 

Output2:

 

Reading and Printing integers from file

 

Output3:

 

Reading and Printing integers from file

 

Output4:

 

Reading and Printing integers from file

 

Example program:

 

To Write and Read more Integer Values in a file.

 

#include<stdio.h>
main()
{ intn,m;
FILE *fp=fopen("num.txt","w");
puts(“Press Cntl+Z to end the values”);
puts("Enter the numbers:");
while(scanf("%d",&n)!=EOF)
putw(n,fp);
fclose(fp);
fp=fopen("num.txt","r");
puts(“Entered values in file are:”);
while((m=getw(fp))!=EOF)
printf("%d\n",m);
}

 

Output:

 

Reading and Printing integers from file