使用檔案概念處理整數資料檔案的 C 程式
在此程式中,我們嘗試整理一個檔案中存在的一個奇數和偶數。然後,我們嘗試將所有奇數寫入 ODD 檔案,並將所有偶數寫入 EVEN 檔案。
以寫入模式開啟檔案 DATA,並在檔案中寫入一些數字,然後關閉它。
再次,
- 以讀取模式開啟 DATA 檔案。
- 以寫入模式開啟 ODD 檔案。
- 以寫入模式開啟 EVEN 檔案。
然後,執行操作以使用 while 迴圈檢查奇數和偶數。
此後關閉所有檔案。
示例
以下是 使用檔案概念處理整數資料檔案的 C 程式 −
#include <stdio.h>
int main(){
FILE *f1,*f2,*f3;
int number,i;
printf("DATA file content is
");
f1=fopen("DATA","w");//creating DATA file
for(i=1;i<=10;i++){
scanf("%d",&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((number=getw(f1))!=EOF){//read from DATA file
if(number %2 ==0)
putw(number,f3); //write to even file
else
putw(number,f2); //write to ODD file
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f3=fopen("EVEN","r");
printf("
contents of ODD file:
");
while((number=getw(f2))!=EOF)
printf("%3d",number);
printf("
contents of EVEN file:
");
while((number=getw(f3))!=EOF)
printf("%3d",number);
fclose(f2);
fclose(f3);
return 0;
}結果
當您執行上述程式時,將獲得以下結果 −
DATA file content is 1 2 3 4 5 6 7 8 9 10 contents of ODD file: 1 3 5 7 9 contents of EVEN file: 2 4 6 8 10
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP