2081 10

BIT102 ยท 2081 ยท 5 marks

Write a program to write N numbers in file "number.txt" and then read it and display only even numbers.

Write a program to write N numbers in file "number.txt" and then read it and display only even numbers. [5]

C ProgrammingChapter 10: File Input Output and PreprocessorFile handling and file operations

Program: Write N Numbers to File and Display Even Numbers

C Program

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

int main() {
    FILE *fp;
    int i, n, num;

    // Step 1: Get N from user
    printf("Enter how many numbers to write: ");
    scanf("%d", &n);

    // Step 2: Open file for writing
    fp = fopen("number.txt", "w");
    if (fp == NULL) {
        printf("Error opening file for writing!\n");
        exit(1);
    }

    // Step 3: Write N numbers to file
    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &num);
        fprintf(fp, "%d\n", num);
    }

    fclose(fp);
    printf("Numbers written to file successfully.\n");

    // Step 4: Open file for reading
    fp = fopen("number.txt", "r");
    if (fp == NULL) {
        printf("Error opening file for reading!\n");
        exit(1);
    }

    // Step 5: Read and display only even numbers
    printf("\nEven numbers from file:\n");
    while (fscanf(fp, "%d", &num) != EOF) {
        if (num % 2 == 0) {
            printf("%d\n", num);
        }
    }

    fclose(fp);
    return 0;
}

Sample Output

Enter how many numbers to write: 6
Enter 6 numbers:
3 8 15 22 7 10

Numbers written to file successfully.

Even numbers from file:
8
22
10

Key Points

StepOperationFunction Used
1Open file for writingfopen("number.txt", "w")
2Write numbers to filefprintf(fp, "%d\n", num)
3Close file after writingfclose(fp)
4Open file for readingfopen("number.txt", "r")
5Read numbers from filefscanf(fp, "%d", &num)
6Check even conditionnum % 2 == 0

Note: Always check if fopen() returns NULL to handle file errors, and always call fclose() after file operations to release resources.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.