Program to read number from file and then write all odd number to file odd.txt and all even number to even.txt

Write a program to read the numbers from the file and then write all odd number to file odd.txt and all even number to even.txt


C Program

#include <stdio.h>

int main()
{

    FILE *readFile;
    int num;
    char buffer[32] = {0};

    // creating a FILE pointer
    FILE *oddfile, *evenfile;

    // open the file in write mode
    oddfile = fopen("odd.txt""w");
    evenfile = fopen("even.txt""w");
    if (oddfile != NULL && evenfile != NULL)
    {
        printf("File created successfully!\n");
    }
    else
    {
        printf("Failed to create the file.\n");
        // exit status for OS that an error occurred
        return -1;
    }

    readFile = fopen("hello.txt""r");

    if (readFile == NULL)
    {
        printf("Can't open file for integers.txt file.\n");
        return -1;
    }
    else
    {
        printf("\nRead Numbers from file:\n");
        while (!feof(readFile))
        {
            fscanf(readFile"%d", &num);
            sprintf(buffer"%d\n"num);
            if (num % 2 == 0)
            {
                fputs(bufferevenfile);
            }
            else
            {
                fputs(bufferoddfile);
            }
        }
        printf("\nEnd of file.\n");

        //close files
        fclose(readFile);
        fclose(oddfile);
        fclose(evenfile);
    }
    return 0;
}
Input File: hello.txt

12 23 45 22 6 7 8 90 23 56 10 100

Output File: odd.txt

23 45 7 23

Output File: even.txt

12 22 6 8 90 56 10 100

Output:
File created successfully!

Read Numbers from file:

End of file.


No comments:

Post a Comment