C program to write even, odd and prime numbers to separate file

Write a C program to input numbers from a file and write even, odd and prime numbers to separate files. How to input numbers from file using fscanf() and write even, odd and prime numbers to different file.

Required knowledge

Basic Input Output, Pointers, File Handling

In last two posts I explained to create file and read string data using fgetc() and fgets(). In this post we will learn about reading formatted input (numbers) from a file using fscanf().

How to input numbers from a file using fscanf()?

int fscanf( FILE * stream, const char * format, ... );
  • It accept a pointer to FILE i.e. stream where to write.
  • format is pointer to constant character containing format string.
  • Next, it accepts memory addresses of variables to fill with input value.
  • On, success it returns count of successful values stored in variable (total successful read). Otherwise returns -1.

Program to write even, odd and prime numbers to separate file

/**
 * C program to input numbers from file and write even, 
 * odd and prime numbers to separate file.
 */

#include <stdio.h>
#include <stdlib.h>


/* Function declarations */
int isEven(const int NUM);
int isPrime(const int NUM);


int main()
{
    /* File pointer to hold reference to different files */
    FILE * fPtrIn,
         * fPtrEven, 
         * fPtrOdd, 
         * fPtrPrime;

    
    int num, success;

    /* 
     * Open all files to perform read/write.
     */
    fPtrIn   = fopen("data/numbers.txt", "r");
    fPtrEven = fopen("data/even-numbers.txt" , "w");
    fPtrOdd  = fopen("data/odd-numbers.txt"  , "w");
    fPtrPrime= fopen("data/prime-numbers.txt", "w");


    /* fopen() return NULL if unable to open file in given mode. */
    if(fPtrIn == NULL || fPtrEven == NULL || fPtrOdd == NULL || fPtrPrime == NULL)
    {
        /* Unable to open file hence exit */
        printf("Unable to open file.\n");
        printf("Please check whether file exists and you have read/write privilege.\n");
        exit(EXIT_FAILURE);
    }


    /* File open success message */
    printf("File opened successfully. Reading integers from file. \n\n");

    // Read an integer and store read status in success.
    while (fscanf(fPtrIn, "%d", &num) != -1)
    {
        /*
         * Write prime, even and odd numbers to different files.
         */
        if (isPrime(num))
            fprintf(fPtrPrime, "%d\n", num);
        else if (isEven(num))
            fprintf(fPtrEven, "%d\n", num);
        else
            fprintf(fPtrOdd, "%d\n", num);

    }


    /* Done with all files, hence close all. */
    fclose(fPtrIn);
    fclose(fPtrEven);
    fclose(fPtrOdd);
    fclose(fPtrPrime);

    printf("Data written to files successfully.");


    return 0;
}


/**
 * Check whether a given number is even or not. The function
 * return 1 if given number is odd, otherwise return 0.
 */
int isEven(const int NUM)
{
    return !(NUM & 1);
}


/**
 * Check whether a number is prime or not. 
 * Returns 1 if the number is prime otherwise 0. 
 */
int isPrime(const int NUM)
{
    int i;  

    // Only positive integers are prime
    if (NUM < 0)
        return 0;
      
    for ( i=2; i<=NUM/2; i++ )    
    {    
        /*   
         * If the number is divisible by any number   
         * other than 1 and self then it is not prime  
         */    
        if (NUM % i == 0)    
        {  
            return 0;  
        }    
    }   
      
    return 1;  
}

You must have data directory created in same workspace. data directory should contain numbers.txt file.

Suppose, if numbers.txt contains

73771782	81296771	79982326	75332246	10128193
81643413	76259734	94432076	50063976	91748657
42311916	-1920042	90747362	53851612	43498487
73193311	96685173	39019033	8630045	59322952

Then the program will create three files even.txt containing all even numbers.

73771782
79982326
75332246
76259734
94432076
50063976
42311916
-1920042
90747362
53851612
59322952
59322952

odd.txt containing all odd numbers.

81296771
81643413
91748657
43498487
96685173
8630045

and prime.txt containing all prime numbers.

10128193
73193311
39019033

Happy coding 😉