实验9 文件 一、实验目的
(1)掌握文件以及缓冲文件系统、文件指针的概念。
(2)学会使用文件打开、关闭、读写等文件操作函数。
(3)掌握对文件进行字符写、块读写的方法。
(4)巩固文件教学单元的知识。
二、实验内容
1、一批整数保存在文本文件in.txt中,统计出的所有素数,保存在out.txt文件中。
重要提示:自己编写的程序命名为test.cpp,本地测试test.cpp时,访问in.txt和out.txt不用带路径,当打包提交时test.cpp中in.txt和out.txt的路径修改为./src/
提交之前,将由题目提供的in.txt和test.cpp放在src文件夹下,然后在src文件夹的上层文件夹中压缩src.zip,保证这个zip文件中有src文件夹和其中的test.cpp文件。
如果使用WinRAR、7z等压缩软件,请注意压缩文件的格式为zip,而不是压缩为其他格式后修改后缀为zip。目前已知使用Windows的资源管理器的右键菜单中的“发送到压缩(zipped)文件夹“功能产生的zip文件不被PTA所接受。Unix的zip命令压缩的文件夹可以接受。
样例输入(即in.txt文件内容):17 33 55 31
扫描二维码关注公众号,回复:
12925118 查看本文章
样例输出(即out.txt文件件内容):2
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1,*fp2;
if((fp1=fopen(".src/in.txt","r"))==NULL)
{
printf("can't open this file.\n");
exit(0);
}
if((fp2=fopen(".src/out.txt","w"))==NULL)
{
printf("can't creat this file.\n");
exit(0);
}
int st,a,i = 0,j;
while(fscanf(fp1,"%d",&st)==1)
{
if(st==2)
{
i++;
continue;
}
int f=1;
for(j=2;j*j<=st;j++)
{
if(st%j==0)
{
f=0;
break;
}
}
if(f)
i++;
}
fclose(fp1);
fprintf(fp2,"%d",i);
fclose(fp2);
return 0;
}