Write a program to read the numbers from the file and then write all odd number to file odd.txt and all even number to even.txt
C Program
#include <stdio.h>int main(){FILE *readFile;int num;char buffer[32] = {0};// creating a FILE pointerFILE *oddfile, *evenfile;// open the file in write modeoddfile = fopen("odd.txt", "w");evenfile = fopen("even.txt", "w");if (oddfile != NULL && evenfile != NULL){printf("File created successfully!\n");}else{printf("Failed to create the file.\n");// exit status for OS that an error occurredreturn -1;}readFile = fopen("hello.txt", "r");if (readFile == NULL){printf("Can't open file for integers.txt file.\n");return -1;}else{printf("\nRead Numbers from file:\n");while (!feof(readFile)){fscanf(readFile, "%d", &num);sprintf(buffer, "%d\n", num);if (num % 2 == 0){fputs(buffer, evenfile);}else{fputs(buffer, oddfile);}}printf("\nEnd of file.\n");//close filesfclose(readFile);fclose(oddfile);fclose(evenfile);}return 0;}
Input File: hello.txt
12 23 45 22 6 7 8 90 23 56 10 100
Output File: odd.txt
23 45 7 23
Output File: even.txt
12 22 6 8 90 56 10 100
Output:
File created successfully!
Read Numbers from file:
End of file.
No comments:
Post a Comment