Answer to Question #219088 in C for Nanba

Question #219088

Implement a program to read a set of integers into a file and find odd and even numbers and store into separate files. Note: Data.txt Even.txt Odd.txt


Runtime input :

1

2

3

4

5

6

7

8

9

10

-1


Output :

1 3 5 7 9

2 4 6 8 10


1
Expert's answer
2021-07-21T01:55:09-0400
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num,num2,even,odd;
FILE *fdata,*fdata2,*feven,*fodd;

// first here opening all files
fdata = fopen("data.txt","w");
feven = fopen("even.txt","w");
fodd = fopen("odd.txt","w");

if(fdata == NULL)
{
printf("Error!");
exit(1);
}
if(fdata2 == NULL)
{
printf("Error!");
exit(1);
}
if(feven == NULL)
{
printf("Error!");
exit(1);
}

//taking user input and storing into data.txt file
printf("Enter input:\n");
do
{
scanf("%d",&num);
if(num!=-1)
{
fprintf(fdata,"%d\n",num);
}
}while(num!=-1);

//here closing data.txt file and again opening for reading it's updated version
fclose(fdata);
fdata2 = fopen("data.txt","r");

while (fscanf(fdata2,"%d", &num2) != EOF)
{
//reading number from data.txt and if it is even then storing into even.txt
//and if input is odd then storing into odd.txt
if((num2%2)==0)
{
fprintf(feven,"%d\n",num2);
}
else
{
fprintf(fodd,"%d\n",num2);
}
}

//closing all the open file
fclose(fdata2);
fclose(feven);
fclose(fodd);

//opening even.txt and odd.txt file for reading
feven = fopen("even.txt","r");
fodd = fopen("odd.txt","r");

//printing all the information present in even.txt and odd.txt file
printf("Odd number: ");
while (fscanf(fodd,"%d", &odd) != EOF)
{
printf("%d",odd);
}
printf("\nEven number: ");
while (fscanf(feven,"%d", &even) != EOF)
{
printf("%d",even);
}

//closing both file
fclose(feven);
fclose(fodd);

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS