Skip to main content

Odd and even numbers to separate files

Short answer

Read integers until user says 'no', writing all to DATA file. Then reopen DATA for reading, and create odd.txt and even.txt. Read each integer, write to odd.txt if odd, else even.txt. Handle file open errors and invalid input.

Write a program in C to read integers from user until user says "no". After reading the data write all the odd numbers to a file named odd.txt and all the even numbers to file named even.txt. (Take care of all possible error conditions to open a new file named DATA.)

Logic.

  1. Create the file DATA in write mode; if fopen() returns NULL, print an error and stop.
  2. Read integers in a loop, write each into DATA, and ask "Continue (yes/no)?" until the user types no. Invalid input stops the loop.
  3. Close DATA, open it again for reading and open odd.txt and even.txt for writing, checking every fopen() for NULL.
  4. Read each number from DATA with fscanf(); write it to odd.txt if x % 2 != 0, otherwise to even.txt.
  5. Close all files.

Error conditions handled: failure of fopen() for each file, and input that is not an integer.

#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE *fd, *fo, *fe;
    int n, x;
    char ans[10];

    fd = fopen("DATA", "w");              /* new file DATA for all numbers */
    if (fd == NULL) {
        printf("Cannot create DATA\n");
        return 1;
    }
    do {
        printf("Enter an integer: ");
        if (scanf("%d", &n) != 1) {       /* invalid input */
            printf("Invalid input\n");
            break;
        }
        fprintf(fd, "%d\n", n);
        printf("Continue (yes/no)? ");
        scanf("%9s", ans);
    } while (strcmp(ans, "no") != 0);
    fclose(fd);

    fd = fopen("DATA", "r");
    fo = fopen("odd.txt", "w");
    fe = fopen("even.txt", "w");
    if (fd == NULL || fo == NULL || fe == NULL) {
        printf("File opening error\n");
        return 1;
    }
    while (fscanf(fd, "%d", &x) == 1) {
        if (x % 2 != 0)
            fprintf(fo, "%d\n", x);
        else
            fprintf(fe, "%d\n", x);
    }
    fclose(fd);
    fclose(fo);
    fclose(fe);
    printf("Done. See odd.txt and even.txt\n");
    return 0;
}

Sample run (numbers 7, 12, 5, 8, 21)

Input: 7 yes 12 yes 5 yes 8 yes 21 no

Enter an integer: Continue (yes/no)? Enter an integer: Continue (yes/no)? Enter an integer: Continue (yes/no)? Enter an integer: Continue (yes/no)? Enter an integer: Continue (yes/no)? Done. See odd.txt and even.txt

odd.txt contains 7, 5, 21 and even.txt contains 12, 8.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →