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