使用文件概念处理整数数据文件的 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