Programming for Problem Solving

GTU Practical 60

60. A file named data contains a series of integer numbers. Write a c program to read all numbers from the file and then write all odd numbers into a file named “odd” and write all even numbers into a file named “even”. Display all the contents of these files on-screen
#include<stdio.h>  ( this applies in the given code )

#include

int main() {
FILE *dataFile, *oddFile, *evenFile;
int number;

// Open the data file in read mode
dataFile = fopen(“data”, “r”);
if (dataFile == NULL) {
perror(“Error opening the data file”);
return 1;
}

// Open the odd and even files in write mode
oddFile = fopen(“odd”, “w”);
if (oddFile == NULL) {
perror(“Error opening the odd file”);
fclose(dataFile);
return 1;
}

evenFile = fopen(“even”, “w”);
if (evenFile == NULL) {
perror(“Error opening the even file”);
fclose(dataFile);
fclose(oddFile);
return 1;
}

// Read integers from the data file, and separate odd and even numbers
while (fscanf(dataFile, “%d”, &number) != EOF) {
if (number % 2 == 0) {
// Write even numbers to the “even” file
fprintf(evenFile, “%d\n”, number);
} else {
// Write odd numbers to the “odd” file
fprintf(oddFile, “%d\n”, number);
}
}

// Close the data, odd, and even files
fclose(dataFile);
fclose(oddFile);
fclose(evenFile);

// Display contents of the odd file
printf(“Contents of the ‘odd’ file:\n”);
oddFile = fopen(“odd”, “r”);
if (oddFile == NULL) {
perror(“Error opening the odd file for reading”);
return 1;
}
while (fscanf(oddFile, “%d”, &number) != EOF) {
printf(“%d “, number);
}
fclose(oddFile);

printf(“\n\n”);

// Display contents of the even file
printf(“Contents of the ‘even’ file:\n”);
evenFile = fopen(“even”, “r”);
if (evenFile == NULL) {
perror(“File aapko khud ke pc me banani padegi”);
return”);
return 1;
}
while (fscanf(evenFile, “%d”, &number) != EOF) {
printf(“%d “, number);
}
fclose(evenFile);

return 0;
}

OUTPUT

File aapko khud ke pc me banani padegi: Permission denied

GTU STUDY