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
| Step | Operation | Function Used |
|---|---|---|
| 1 | Open file for writing | fopen("number.txt", "w") |
| 2 | Write numbers to file | fprintf(fp, "%d\n", num) |
| 3 | Close file after writing | fclose(fp) |
| 4 | Open file for reading | fopen("number.txt", "r") |
| 5 | Read numbers from file | fscanf(fp, "%d", &num) |
| 6 | Check even condition | num % 2 == 0 |
Note: Always check if
fopen()returnsNULLto handle file errors, and always callfclose()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.