验收代码(杂合代码)
main文件
#include"vivi.h"
//函数封装
using namespace std;
int main(int argc,char *argv[])
//命令行参数
{
FILE *fp;
//文件指针
if(!read(&fp,argv[2]))
//将文件指针传入函数形参
{
return 0;}
if(s_cmp(argv[1])) //识别指令
opt1(&fp,argv[3]);
else opt2(&fp,argv[3]);
fclose(fp); //关闭文件
return 0;
}
vivi.h头文件
#include<bits/stdc++.h>
struct node{
int id,p;
char s[50];
float a,b,c;
};
//定义结构体
bool s_cmp(char s1[])//识别指令函数
{
if(s1[0]=='1')return 1;
return 0;
}
bool read(FILE** fp,char s[])//打开并读入指定文件
{
if ((*fp=fopen(s,"r"))==NULL){//打开文件,并判断是否有打开错误,增加容错率
printf("打开文件%s出现错误\n",s);
return 0;}
//以下显示文件内容
//增加代码安全性能维护
return 1;
}
void opt1(FILE** fp,char s[])
{
int cnt=-1;
node stu[10];
char temp[1024]; //读文件的缓冲
while(fgets(temp,1024,*fp)!=NULL)//读入一行字符串并且判断文件是否结束,维护程序的稳健性
{
++cnt;//记录读入记录的总数
sscanf(temp,"%d %s %f %f %f %d",&stu[cnt].id,stu[cnt].s,&stu[cnt].a,&stu[cnt].b,&stu[cnt].c,&stu[cnt].p);
//对字符串进行处理,依次读入结构体数组
printf("%d, %s, %.1f, %.1f, %.1f, %d\n",stu[cnt].id,stu[cnt].s,stu[cnt].a,stu[cnt].b,stu[cnt].c,stu[cnt].p);
//按照文件要求格式进行屏幕输出
}
//scanf("%s",filename);
//printf("%s\n",s);
FILE *fs=fopen(s,"w");
fwrite(stu,cnt+1,sizeof(struct node),fs);//用fwrite将结构体数组写入dat文件
//我们是从0开始计数,故总数比cnt多1
fclose(fs);
}
void opt2(FILE** fp,char s[])
{
freopen(s,"w",stdout);//用freopen将数据写入对应文件
node stu[10];
fread(stu,sizeof(node),4,*fp);//使用fread进行结构体数组的文件读入
for(int i=0;i<4;i++)
printf("%d, %s, %.1f, %.1f, %.1f, %d\n",stu[i].id,stu[i].s,stu[i].a,stu[i].b,stu[i].c,stu[i].p);//将结构体写入对应的文件里
}
文档要求
1.文本文件读写
#include<bits/stdc++.h>
using namespace std;
struct node{
int id,p;
char s[50];
float a,b,c;
}stu[10];
int main()
{
freopen("testfile.txt","r",stdin);//使用freopen进行文件读入
freopen("testfile2.txt","w",stdout);//使用freopen进行文件输出
char temp[1000];
int cnt=-1;//计算读入数据数量
while((scanf("%d",&stu[++cnt].id))!=EOF) //判断文件是否达到结尾,若达到则停止文件输入
scanf("%s %f %f %f %d",stu[cnt].s,&stu[cnt].a,&stu[cnt].b,&stu[cnt].c,&stu[cnt].p);//依次读入结构体数据
for(int i=0;i<cnt;i++)
printf("%d, %s, %.1f, %.1f, %.1f, %d\n",stu[i].id,stu[i].s,stu[i].a,stu[i].b,stu[i].c,stu[i].p);//按照格式化输出数据
}
2.二进制文件读写
将1个100个元素的浮点数组、1个100个字符的字符数组分别写入到二进制文件、文本文件(共四个文件),比较文本/二进制文件的大小、内容的差异。
#include<bits/stdc++.h>
#define inc(i,l,r) for(int i=l;i<=r;i++)
using namespace std;
int main()
{
freopen("in1.txt","w",stdout);
srand(time(NULL));
inc(i,1,100)
printf("%f ",float(1000+rand()%(100000-1000+1))/1000.0);
return 0;
}
#include<bits/stdc++.h>
#define inc(i,l,r) for(int i=l;i<=r;i++)
using namespace std;
int main()
{
freopen("in2.txt","w",stdout);
srand(time(NULL));
inc(i,1,100)
{
printf("%c\n",char(76+i%10));
}
return 0;
}
#include<bits/stdc++.h>
#define inc(i,l,r) for(int i=l;i<=r;i++)
using namespace std;
int main()
{
freopen("in3.dat","wb",stdout);
srand(time(NULL));
inc(i,1,100)
printf("%f ",float(1000+rand()%(100000-1000+1))/1000.0);
return 0;
}
#include<bits/stdc++.h>
#define inc(i,l,r) for(int i=l;i<=r;i++)
using namespace std;
int main()
{
freopen("in4.dat","wb",stdout);
srand(time(NULL));
inc(i,1,100)
{
printf("%c\n",char(76+i%10));
}
return 0;
}