0% found this document useful (0 votes)
4 views1 page

5

The document provides a C program that collects a list of N numbers from user input and writes them to a file named 'numbers.txt'. It then reads the numbers from this file, separates them into even and odd numbers, and writes them to two separate files called 'even_file.txt' and 'odd_file.txt'. The program includes error handling for file operations and confirms successful writing of the separated numbers.

Uploaded by

ankit.sin1109
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

5

The document provides a C program that collects a list of N numbers from user input and writes them to a file named 'numbers.txt'. It then reads the numbers from this file, separates them into even and odd numbers, and writes them to two separate files called 'even_file.txt' and 'odd_file.txt'. The program includes error handling for file operations and confirms successful writing of the separated numbers.

Uploaded by

ankit.sin1109
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Ques5 - Use the concept of File Handling, to Write a program in C, to collect a list of

N numbers in a file, and separate the even and odd numbers from the given list of
N numbers, and put them in two separate files namely even_file and odd_file, respec vely.

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

int main() {
FILE *inputFile, *evenFile, *oddFile;
int n, i, num;

// Open input file to write the numbers


inputFile = fopen("numbers.txt", "w");
if (inputFile == NULL) {
prin ("Error opening file for wri ng.\n");
return 1;
}

prin ("Enter the number of elements (N): ");


scanf("%d", &n);

prin ("Enter %d numbers:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &num);
fprin (inputFile, "%d\n", num);
}
fclose(inputFile);

// Open input file for reading, and two others for wri ng even and odd numbers
inputFile = fopen("numbers.txt", "r");
evenFile = fopen("even_file.txt", "w");
oddFile = fopen("odd_file.txt", "w");

if (inputFile == NULL || evenFile == NULL || oddFile == NULL) {


prin ("Error opening one or more files.\n");
return 1;
}

while (fscanf(inputFile, "%d", &num) != EOF) {


if (num % 2 == 0)
fprin (evenFile, "%d\n", num);
else
fprin (oddFile, "%d\n", num);
}

prin ("Even and odd numbers have been wri en to 'even_file.txt' and 'odd_file.txt'.\n");

fclose(inputFile);
fclose(evenFile);
fclose(oddFile);

return 0;
}
C

You might also like