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.
");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading integers from file.
");
// Read an integer and store read status in success.
while (fscanf(fptrinput, "%d", &num) != -1){
if (prime(num))
fprintf(fptrprime, "%d
", num);
else if (even(num))
fprintf(fptreven, "%d
", num);
else
fprintf(fptrodd, "%d
", 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP