Pages

Sunday, 22 October 2017

Even Odd Separation File Creation

Q : Write a ‘C’ Program to create a file of numbers and copy odd number into second file and even number into third file.

Solution :


#include<stdio.h>
#include<conio.h>
void main()
{
     FILE *source,*even_file,*odd_file;
     char ch;
     clrscr();
     source=fopen("test.txt","r");
     even_file=fopen("even.txt","w");
     odd_file=fopen("o
dd.txt","w");
     if(source==NULL)
          printf("\n\tUnable to open source file");
     else if(even_file==NULL)
          printf("\n\tEven file creation error");
     else if(odd_file==NULL)
          printf("\n\tOdd file creation error");
     else
     {
          while(1)
          {
              ch=fgetc(source);
              if(ch==EOF)
                   break;
              if(ch%2==0)
                   fputc(ch,even_file);
              else
                   fputc(ch,odd_file);
          }
     }
     printf("\n\tSource file content\n");
     fseek(source,0,SEEK_SET);
     while(1)
     {
          ch=fgetc(source);
          if(ch==EOF)
              break;
          printf("%c",ch);
     }
     printf("\n\tEven file content\n");
     fclose(source);
     fclose(even_file);
     fclose(odd_file);
     even_file=fopen("even.txt","r");
     odd_file=fopen("odd.txt","r");
     while(1)
     {
          ch=fgetc(even_file);
          if(ch==EOF)
              break;
          printf("%c",ch);
     }
     fclose(even_file);
     printf("\n\tODD file content\n");
     while(1)
     {
          ch=fgetc(odd_file);
          if(ch==EOF)
              break;
          printf("%c",ch);
     }
     fclose(odd_file);
     getch();

}

No comments:

Post a Comment