SUMMER TRAINING Free Tutorials  Go To Your University  Placement Preparation 
Project Based Best Summer Training Courses in Jaipur
Join our Telegram Channel To take free Online Courses
0 like 0 dislike
132 views
in GTU B.E. (CSE-I-Sem) Programming For Problem Solving Lab by Goeduhub's Expert (7.1k points)

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

1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.1k points)
edited by
 
Best answer

Odd Even Check From a File

In this program we are going to read a stream of numbers from a text file and then append the odd number in odd file and even number into the even file as in the following example.

To learn basics of file handling Click Here.

Example :

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void main()
{
clrscr();
ifstream fs;
ofstream fodd,feven;
int i=0,j=0;

//To accept file name from user declaration of string characters
char ch, fname[20],even[20],odd[20];
printf("Enter source file name with extension (like files.txt) : ");

//gets() function to accept file name
gets(fname);

//Open the file fname in read mode
fs.open(fname,ios::in);

//if file fails to open
if(!fs)
{
printf("Error in opening source file..!!");
getch();
exit(1);
}

//Accepting odd dile and even file names
printf("Enter odd number file name with extension (like filet.txt) : ");
gets(odd);

//Opening file in append mode
fodd.open(odd,ios::app);

printf("Enter even number file name with extension (like filet.txt) : ");
gets(even);
feven.open(even,ios::app);

//if even or odd file fails to open
if(!fodd || !feven)
{
printf("Error in opening target file..!!");
fs.close();
getch();
exit(2);
}

//While the end of the stream
while(fs.eof()==0)
{
j=0;

//read integer value from the file
fs>>i;
j=i;
i=0;

//if even append in even file
if(j%2==0)
{
feven<<j;
}

//else append in odd file
else
fodd<<j;
}
printf("\nOperation successful");
fs.close();
feven.close();
fodd.close();
getch();
}

Output :


For More GTU C Programming Lab Experiments Click Here

Our Mentors(For AI-ML)


Sharda Godara Chaudhary

Mrs. Sharda Godara Chaudhary

An alumna of MNIT-Jaipur and ACCENTURE, Pune

NISHA (IIT BHU)

Ms. Nisha

An alumna of IIT-BHU

Related questions

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...