The getw() and putw() functions in C programming

The getw() and putw() functions in C programming are used to write integer data into file and read integer data from the file respectively. These are similar to getc() and putc() to read integer values. These are only useful when handling with integer oriented data. The general for are


                      putw(integer,fp);
                      getw(fp);


   The putw() function takes two arguments one as integer data, second one is file pointer , where you need to write integer data. The getw() takes only one argument file pointer, that is from where we can get integer data.

      The following program show the above two functions are work.


#include<stdio.h>

main()

{

FILE *f1,*f2,*f3;

int number,i;

printf(" contents of DATA file");

f1=fopen("DATA","w");

for(i=1;i<=30;i++)

{

scanf("%d",&number);

putw(number,f1);           /* writing integers to DATA file */

}

fclose(f1);

f1=fopen("DATA","r");

f2=fopen("EVEN","w");

f3=fopen("ODD","w");

while((number=getw(f1))!=EOF)

{

if(number%2= = 0)

putw(number,f2);     /* writing even integers to EVEN file */

else

putw(number,f3); /* writing odd integers to ODD file */

}

fclose(f1);

fclose(f2);

fclose(f3);

f2=fopen("EVEN""r");

f3=fopen("ODD","r");

printf("\n \n contents of EVEN file \n \n");

while((number=getw(f2))!=EOF)

printf("%4d",number);

 

 

printf("\n \n contents of ODD file \n \n");

while((number=getw(f3))!=EOF)

printf("%4d",number);

 

fclose(f2);

fclose(f3);

}

 



 In the above program, we first write all integer data to a file called "DATA"  and close the file. Next we have opened two files, EVEN,ODD. All the even integers write to the EVEN file, all the odd integers are write to the file ODD. Finally we are printing all the even and odd integers from the files.

No comments: