Logo 
Search:

C Programming Articles

Submit Article
Home » Articles » C Programming » Homework HelpRSS Feeds

Program to writes numbers in a file and read and find odd or even numbers from it

Posted By: Ellis Evans     Category: C Programming     Views: 56272

Write a program which reads numbers from a user and writes it in a file. Also find odd and even numbers by reading that file and store it in 2 separate files odd and even.

Code for Program to writes numbers in a file and read and find odd or even numbers from it in C Programming

#include<stdio.h>
#include<conio.h>

void main()
{
    FILE *f1,*f2,*f3;
    int number,i;
    clrscr();

    printf("Contents of DATA file\n\n");
    f1 = fopen("DATA","w");  /* create a data file */
for(i=1;i<=30;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) /* Read from Data file */
{ if(number%2==0) putw(number,f3); else putw(number,f2); } fclose(f1); fclose(f2); fclose(f3); f2 = fopen("ODD","r"); f3 = fopen("EVEN","r"); printf("\n\nContents of ODD file \n\n"); while((number = getw(f2)) != EOF) printf("%4d",number); printf("\n\nContents of EVEN file \n\n"); while((number = getw(f3)) != EOF) printf("%4d",number); fclose(f2); fclose(f3); getch(); }
  
Share: 



Ellis Evans
Ellis Evans author of Program to writes numbers in a file and read and find odd or even numbers from it is from London, United Kingdom.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
SANDIP PAL from India Comment on: Dec 29
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main()
{
ofstream fout;
vector<int>v1;
int input;
int n;
fout.open("All number.txt",ios::out);
if(fout.fail())
{
cout<<"File can not open"<<endl;
exit(0);
}
else
{
cout<<"Enter the size of the array"<<endl;
cin>>n;
cout<<"Enter the numbers"<<endl;
for(int i=0;i<n;i++)
{
cin>>input;
v1.push_back(input);
fout<<input<<endl;
}
fout.close();
}
ofstream dout,nout;
ifstream fin;
int p;
fin.open("All number.txt",ios::in);
dout.open("Even number.txt",ios::out);
nout.open("Odd number.txt",ios::out);
while(!fin.eof())
{
fin>>p;
if(p%2==0)
{
dout<<p<<endl;
}
else
{
nout<<p<<endl;
}

}
cout<<"Separation complete"<<endl;
nout.close();
dout.close();
fin.close();
}


I have written this code in c++. But my output is not correct.If last number is even then this number exist TWICE in Even number.txt file, if last number is odd then this number exist TWICE in Odd number.txt file.Please help me.

View All Comments