Digital जीवन

Free Online Education for India...

Full width home advertisement

Computer Basic

C Programming

Engineering Graphics

Post Page Advertisement [Top]

Dr. A.P.J. Abdul Kalam Technical University, Lucknow

KCS151 / KCS251 Programming for Problem Solving - Using C Language


Lab Exercises


39. Write a program to read numbers from a file and then write all ‘odd’ numbers to file ODD.txt & all even to file EVEN.txt.


/*
 File: Prgrm39.c
 Author: Aditya Saini
 Date: Jan 20, 2021
 Description: Program to read number from file and then write all ‘odd’ number to file ODD.txt
 & all even to file EVEN.txt.
*/

#include <stdio.h>

int main (void)
{
     FILE *f_ptr, *f_odd, *f_even;
     char path_f[256], path_o[256], path_e[256];
     int num;

     //Input file path
     printf ("Input file path: ");
     fflush (stdin);
     gets (path_f);

     //Open file
     f_ptr = fopen (path_f, "r");
     if (f_ptr == NULL)
     {
          printf ("Error! Unable to open file.");
          return 0;
     }

     //Input Odd file path
     printf ("Input Odd.txt file path: ");
     fflush (stdin);
     gets (path_o);

     //Open Odd file
     f_odd = fopen (path_o, "w");
     if (f_odd == NULL)
     {
          printf ("Error! Unable to save Odd.txt file.");
          return 0;
     }

     //Input Even file path
     printf ("Input Even.txt file path: ");
     fflush (stdin);
     gets (path_e);

     //Open Even file
     f_even = fopen (path_e, "w");
     if (f_even == NULL)
     {
          printf ("Error! Unable to save Even.txt file.");
          return 0;
     }

     //Read integer from first file and write square in second file
     while (fscanf (f_ptr, "%d", &num) != EOF)
     {
          if (num %2 == 0)
               fprintf (f_even, "%d ", num);
          else
               fprintf (f_odd, "%d ", num);
     }

     //Close files
     fclose (f_ptr);
     fclose (f_odd);
     fclose (f_even);

     return 0;
};



No comments:

Post a Comment

Please do not post spam links.

Bottom Ad [Post Page]

| Designed by Colorlib