将偶数、奇数和质数存储到单独文件中的 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){
      /* Unable to open file hence exit */
      printf("Unable to open file.\n");
      exit(EXIT_FAILURE);
   }
   /* File open success message */
   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("数据写入成功。");
   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.
数据写入成功。

解释

下面给出了用于将偶数、奇数和质数存储到单独文件中的程序的解释 -

Input file:
numbers.txt file contains: 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17
Which is open in read mode (already exists file)
Separated even, odd and prime numbers in separate file after execution
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