4. 实验任务4
task4.c源码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE* fp;
char ch;
int cnt = 0;
fp = fopen("data4.txt", "r");
if (fp == NULL) {
printf("fail to open the file\n");
exit(0);
}
while (!(feof(fp))) {
ch = fgetc(fp);
if (ch == ' ' || ch == '\n') continue;
if (ch == EOF) break;
cnt++;
}
fclose(fp);
printf("data4.txt中有字符%d个\n", cnt);
return 0;
}
截图:
5. 实验任务5
task5.c
截图:
6. 实验任务6
源代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define N 80
#define M 5
typedef struct{
long number;
char name[20];
char classname[20];
}STU;
void finput(STU stu[],int n);//从list.txt读入
void foutput(STU stu[],STU lucky[],int m);//取随机数,并写入lucky.txt
void output(STU lucky[],int n);//屏幕上输出
int main(){
STU stu[N],lucky[5];
finput(stu,N);
foutput(stu,lucky,M);
output(lucky,M);
return 0;
}
void finput(STU stu[],int n){
FILE *fp;
int i;
fp = fopen("list.txt","r");
if(fp==NULL){
printf("fail\n");
exit(0);
}
while(!feof(fp))
for(i=0;i<N;++i)
fscanf(fp,"%d%s%s",&stu[i].number,stu[i].name,stu[i].classname);
fclose(fp);
}
void foutput(STU stu[],STU lucky[],int m){
FILE *fp;
int i;
fp = fopen("lucky.txt", "w");
if (fp==NULL) {
printf("fail\n");
exit(0);
}
srand(time(NULL));
for(i=0;i<m;++i){
int number=rand()%N;//在0,N-1间取随机整数
lucky[i]=stu[number];
}
for(i=0;i<m;++i)
fprintf(fp,"%d\t%s\t%s\n",lucky[i].number,lucky[i].name,lucky[i].classname);
fclose(fp);
}
void output(STU lucky[],int n){
int i;
for(i=0;i<n;++i)
printf("%d\t%s\t%s\n",lucky[i].number,lucky[i].name,lucky[i].classname);
}
截图: