facebook like button

04 June, 2011

program 56: sorting odd and even

The need:
    This is a simple program to show some more functions to access a file. This program shows how getw() and putw() functions can be used to get and print integers to and from a file respectively.

The code:
-------------------------------------------- 
#include<stdio.h>
#include<stdlib.h>
main()
{
    FILE *f1,*f2,*f3;
    int i,j=0;
    f1=fopen("Numbers.txt","w");
    printf("Enter some integers. Enter -1 to end.\n");
    while(j<20)
    {
        scanf("%d",&i);
        j++;
        if(i==-1)
        break;
        putw(i,f1);           
    }
    fclose(f1);   
    f1=fopen("Numbers.txt","r");
    f2=fopen("Odd.txt","w");
    f3=fopen("Even.txt","w");
    while((i=getw(f1))!=EOF)
    {
        if(i%2==0)
        putw(i,f3);                   
        else
        putw(i,f2);                   
    }
    fclose(f1);
    fclose(f2);
    fclose(f3);
    f1=fopen("Numbers.txt","r");
    f2=fopen("Odd.txt","r");
    f3=fopen("Even.txt","r");
    printf("content of file Number");
    while((i=getw(f1))!=EOF)
        printf("%4d",i);
    printf("\n\ncontent of file Odd");
    while((i=getw(f2))!=EOF)
        printf("%4d",i);
    printf("\n\ncontent of file Even");
    while((i=getw(f3))!=EOF)
        printf("%4d",i);
        printf("\n\n");
    fclose(f1);
    fclose(f2);
    fclose(f3);
}
--------------------------------------------

The approach:
    First the program asks user to input some integers (max 20) and takes until user enters -1 or 20 numbers are entered. These numbers are then written to a file called numbers.txt which was opened in write mode. After that the numbers.txt is closed. Again numbers.txt is opened in read mode and each number is scanned from file. Meanwhile files odd.txt and even.txt are opened in write mode and each number which was scanned from numbers.txt is checked for odd and even (if condition does the task) and put in the corresponding file.



Remarks:

1. All of you will get correct output on the terminal but some of you may not be able to see the correct content in files created. getw() and putw() sometime face this problem due to different encoding of characters.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply