Problem 60

author
By Supreme2023-03-16
Problem Statement :
A file named data contains series of integer numbers. Write a c program to read all numbers from file and then write all odd numbers into file named “odd” and write all even numbers into file named “even”. Display all the contents of these file on screen
Code:

#include<stdio.h>

int main() {

/*60. A file named data contains series of integer numbers. Write a c program to read all
numbers from file and then write all odd numbers into file named “odd” and write all
even numbers into file named “even”. Display all the contents of these file on screen*/

printf("\tAnalysis Of Data Of File\n");
printf("==========================================\n");

FILE * f1, * f2, * f3;
int number, i, n = 10;

// printf("Contents of DATA file\n\n");
//
// f1 = fopen("DATA", "w");
//
// for (i = 0; i < n; 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) {
if (number % 2 == 0) {
putw(number, f3);
} else {
putw(number, f2);
}
}

fclose(f1);
fclose(f2);
fclose(f3);

f1 = fopen("DATA", "r");
f2 = fopen("ODD", "r");
f3 = fopen("EVEN", "r");

printf("\n\nContents Of DATA File :\n\n");

while ((number = getw(f1)) != EOF) {
printf("%d ", number);
}

printf("\n\nContents Of ODD File :\n\n");

while ((number = getw(f2)) != EOF) {
printf("%d ", number);
}

printf("\n\nContents Of EVEN File :\n\n");

while ((number = getw(f3)) != EOF) {
printf("%d ", number);
}

fclose(f2);
fclose(f3);
return 0;
}

Description :
  • This program reads a series of integers from a file named "DATA" and writes all the odd numbers into a file named "ODD" and all the even numbers into a file named "EVEN". Then, it displays the contents of all three files on the screen.
  • Declare three file pointers: f1, f2, and f3.
  • Open the "DATA" file in read mode and the "ODD" and "EVEN" files in write mode using the file pointers.
  • Read all the integers from the "DATA" file one by one, and check if each integer is even or odd using the modulo operator.
  • Write the even numbers into the "EVEN" file and odd numbers into the "ODD" file using the putw() function.
  • Close all the files.
  • Open the "DATA", "ODD", and "EVEN" files in read mode using the file pointers.
  • Display the contents of the "DATA" file using a while loop and getw() function.
  • Display the contents of the "ODD" file using a while loop and getw() function.
  • Display the contents of the "EVEN" file using a while loop and getw() function.
  • Close the "ODD" and "EVEN" files.
  • Return 0 to indicate successful program execution.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.