偶数、奇数、素数を別々のファイルに保存するCプログラム
ファイルはディスク上の物理的な保存場所であり、ディレクトリはファイルを整理するために使用される論理パスです。ディレクトリ内にファイルが存在します。
ファイルに対して実行できる3つの操作は次のとおりです-
- ファイルを開きます。
- ファイルを処理します(読み取り、書き込み、変更)。
- ファイルを保存して閉じます。
プログラム
以下は、偶数、奇数、素数を別々のファイルに保存する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");
// Read an integer and store read status in success.
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 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
-
Pythonプログラムでのテキストファイルの読み取りと書き込み
このチュートリアルでは、Pythonでのファイル処理について学習します。組み込み関数を使用して、Pythonでファイルを簡単に編集できます。 Pythonで編集できる2種類のファイルがあります 。それらが何であるか見てみましょう。 テキストファイル テキストファイルは、英語のアルファベットを含む通常のファイルです。ファイルに存在するコンテンツをテキストと呼びます。 バイナリファイル バイナリファイルには、0と1のデータが含まれています。その言語を理解することはできません。 ファイルアクセスモード Pythonでファイルを操作するときはいつでも 、ファイルのアクセスモードにつ
-
偶数要素と奇数要素を2つの異なるリストに分割するPythonプログラム。
このプログラムでは、ユーザー入力リストを作成し、要素は奇数要素と偶数要素の混合物です。私たちの仕事は、これらのリストを2つのリストに分割することです。 1つは奇数の要素を含み、もう1つは偶数の要素を含みます。 例 Input: [1, 2, 3, 4, 5, 9, 8, 6] Output Even lists: [2, 4, 8, 6] Odd lists: [1, 3, 5, 9] アルゴリズム Step 1 : create a user input list. Step 2 : take two empty list one for odd and another for eve