Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C แยกตัวเลขคู่ คี่ และเฉพาะ เก็บในไฟล์แยกกัน

ไฟล์เป็นตำแหน่งจัดเก็บจริงบนดิสก์ การดำเนินการ: เปิด, ประมวลผล, บันทึกและปิด

โปรแกรม

โปรแกรม C แยกตัวเลขคู่ คี่ และเฉพาะ เก็บในไฟล์แยกกัน:

#include <stdio.h> #include <stdlib.h> /* Function declarations */ int even(const int num); int prime(const int num); int main(){    FILE * fptrinput,    * fptreven,    * fptrodd,    * fptrprime;    int num, success;    fptrinput = fopen("numbers.txt", "r");    fptreven = fopen("even-numbers.txt" , "w");    fptrodd = fopen("odd-numbers.txt" , "w");    fptrprime= fopen("prime-numbers.txt", "w");    if(fptrinput == NULL || fptreven == NULL || fptrodd == NULL || fptrprime == NULL){       printf("Unable to open file.\n");       exit(EXIT_FAILURE);    }    printf("File opened successfully. Reading integers from file. \n\n");    while (fscanf(fptrinput, "%d", &num) != -1){       if (prime(num))          fprintf(fptrprime, "%d\n", num);       else if (even(num))          fprintf(fptreven, "%d\n", num);       else          fprintf(fptrodd, "%d\n", num);    }    fclose(fptrinput);    fclose(fptreven);    fclose(fptrodd);    fclose(fptrprime);    printf("Data written successfully.");    return 0; } int even(const int num){    return !(num & 1); } int prime(const int num){    int i;    if (num < 0)       return 0;    for ( i=2; i<=num/2; i++ ) {       if (num % i == 0) {          return 0;       }    }    return 1; }

ผลลัพธ์

File opened successfully. Reading integers from file. Data written successfully.

คำอธิบาย

Input file: numbers.txt contains: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
even-numbers.txt contains: 4 6 8 10 12 14 16
odd-numbers.txt contains: 9 15
prime-numbers.txt contains: 1 2 3 5 7 11 13 17