95 date:2021.2.18
要点: 文件指针
详细代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void WriteText(FILE *);
void ReadText(FILE *);
void main()
{
FILE *fp;
if((fp=fopen("myfile4.txt","w"))==NULL)
{
printf(" open fail!!\n"); exit(0);}
WriteText(fp);
fclose(fp);
if((fp=fopen("myfile4.txt","r"))==NULL)
{
printf(" open fail!!\n"); exit(0);}
ReadText(fp);
fclose(fp);
}
/**********found**********/
void WriteText(FILE *fw)
{
char str[81];
printf("\nEnter string with -1 to end :\n");
gets(str);
while(strcmp(str,"-1")!=0) {
/**********found**********/
fputs(str,fw); fputs("\n",fw);
gets(str);
}
}
void ReadText(FILE *fr)
{
char str[81];
printf("\nRead file and output to screen :\n");
fgets(str,81,fr);
while( !feof(fr) ) {
/**********found**********/
printf("%s",str);
fgets(str,81,fr);
}
}
要点: 结构体
详细代码如下:
#include <stdio.h>
#define N 16
typedef struct
{
char num[10];
int s;
} STREC;
int fun( STREC *a, STREC *b )
{
/*
analyse:
遍历寻找最低分数的学生 -> 将其存入b数组中 ->
return 分数最低的学生人数;
*/
int i, j=0 ,min = a[0].s;
for(i = 0; i < N; i++)
if(min > a[i].s)
min = a[i].s; //找到最小值
for(i = 0; i<N; i++)
if( min == a[i].s)
b[j++] = a[i]; //找出与最小值相等的学生记录并存入结构体b中
return j;
/* error:
int i,k = 0,min = a[0].s;
for( i = 0; i<N; i++)
{
if(a[i].s < min)
{
min = a[i].s;
*b = a[i];
k++;
}
}
return k;
*/
}
void main()
{
STREC s[N]={
{
"GA05",85},{
"GA03",76},{
"GA02",69},{
"GA04",85},
{
"GA01",91},{
"GA07",72},{
"GA08",64},{
"GA06",87},
{
"GA015",85},{
"GA013",91},{
"GA012",64},{
"GA014",91},
{
"GA011",91},{
"GA017",64},{
"GA018",64},{
"GA016",72}};
STREC h[N];
int i,n;FILE *out ;
n=fun( s,h );
printf("The %d lowest score :\n",n);
for(i=0;i<n; i++)
printf("%s %4d\n",h[i].num,h[i].s);
printf("\n");
out = fopen("out.dat","w") ;
fprintf(out, "%d\n",n);
for(i=0;i<n; i++)
fprintf(out, "%4d\n",h[i].s);
fclose(out);
}