问题:
文本的输入输出,从一个文件中提取若干数字,并将其中的素数输出到另一个文件中
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int prime(int n) //素数判定
{
int i;
if(n<=1) return -1;
for(i=2;i<=(int)sqrt(n)+1;i++)
{
if((n%i)==0) return -1;
}
return 1;
}
int main()
{
FILE *fp1,*fp2;
char ch,str[1000];
char strr[1000]={0};
int i;
int k=0;
if((fp1=fopen("D:\\test1.txt","w+"))==NULL) //先把内容写入文件
{
printf("open file error");
exit(0);
}
gets(str);
fputs(str,fp1);
fclose(fp1); //关闭第一个文件
if((fp1=fopen("D:\\test1.txt","r"))==NULL) //重新打开第一个文件
{
printf("open file error");
exit(0);
}
if((fp2=fopen("D:\\test2.txt","w+"))==NULL) //重新打开目标文件
{
printf("open file error");
exit(0);
}
while(!feof(fp1)) //当未读到文件结束符
{
for(i=0;i<strlen(str);i++)
{
ch=fgetc(fp1);
if((int)(ch-'0')>=0&&(int)(ch-'0')<=9)
{
strr[k++]=ch;
}
}
//strr[k]="\0";
}
int kk=atoi(strr);
if(prime(kk)==1)
{
printf("是素数");
}
else
{
printf("非素数");
}
fputs(strr,fp2);
fclose(fp1);
putchar(10);
fclose(fp2);
return 0;
}