Computer >> Computer tutorials >  >> Programming >> C programming

C program to handle integer data files using file concepts


In this program, we are trying to sort out the odd numbers and even numbers that are present in one file. Then, we try to write all odd numbers in ODD file and even numbers into EVEN file.

Open a file DATA in write mode and write some numbers into the file and later on close it.

Again,

  • Open DATA file in read mode.
  • Open ODD file in write mode.
  • Open EVEN file in write mode.

Then, perform the operations to check odd and even numbers by using while loop.

After that close all files.

Example

Following is the C program to handle integer data files using file concepts

#include <stdio.h>
int main(){
   FILE *f1,*f2,*f3;
   int number,i;
   printf("DATA file content is\n");
   f1=fopen("DATA","w");//creating DATA file
   for(i=1;i<=10;i++){
      scanf("%d",&number);
      if(number==-1)
         break;
      putw(number,f1);
   }
   fclose(f1);
   f1=fopen("DATA","r");
   f2=fopen("ODD","w");
   f3=fopen("EVEN","w");
   while((number=getw(f1))!=EOF){//read from DATA file
      if(number %2 ==0)
         putw(number,f3); //write to even file
      else
         putw(number,f2); //write to ODD file
   }
   fclose(f1);
   fclose(f2);
   fclose(f3);
   f2=fopen("ODD","r");
   f3=fopen("EVEN","r");
   printf("\n contents of ODD file:\n");
   while((number=getw(f2))!=EOF)
      printf("%3d",number);
   printf("\n contents of EVEN file:\n");
   while((number=getw(f3))!=EOF)
      printf("%3d",number);
   fclose(f2);
   fclose(f3);
   return 0;
}

Output

When you execute the above mentioned program, you get the following output −

DATA file content is
1
2
3
4
5
6
7
8
9
10
contents of ODD file:
1 3 5 7 9
contents of EVEN file:
2 4 6 8 10