//学生记录由学号和成绩组成,N名学生的数据已放入主函数中的结构体数组中,fun函数:把分数最低的学生数据放入数组b所指的数组中,分数最低的学生可能不止一个。人数返回。
1 #include <stdio.h> 2 #define N 16 3 typedef struct 4 { char num[10]; 5 int s; 6 } STREC; 7 int fun( STREC *a, STREC *b ) 8 { 9 STREC *c; 10 c = a; 11 int min = c->s; 12 int s = 0; 13 for (int i = 0; i < N; i++) 14 { 15 c++; 16 if (c->s < min) min = c->s; 17 } 18 for (int j = 0; j < N; j++) 19 { 20 if (a->s == min) 21 { 22 s++; 23 *b = *a;//注意赋值方式 24 b++; 25 } 26 a++; 27 } 28 return s; 29 } 30 31 void main() 32 { STREC s[N]={{"GA05",85},{"GA03",76},{"GA02",69},{"GA04",85}, 33 {"GA01",91},{"GA07",72},{"GA08",64},{"GA06",87}, 34 {"GA015",85},{"GA013",91},{"GA012",64},{"GA014",91}, 35 {"GA011",91},{"GA017",64},{"GA018",64},{"GA016",72}}; 36 STREC h[N]; 37 int i,n;FILE *out ; 38 n=fun( s,h ); 39 printf("The %d lowest score :\n",n); 40 for(i=0;i<n; i++) 41 printf("%s %4d\n",h[i].num,h[i].s); 42 printf("\n"); 43 out = fopen("out.dat","w") ; 44 fprintf(out, "%d\n",n); 45 for(i=0;i<n; i++) 46 fprintf(out, "%4d\n",h[i].s); 47 fclose(out); 48 }
//从键盘输入若干字符串,写入文件myfile4中,用-1作字符输入结束的标志,然后将文件的内容显示在屏幕上,文件的读写分别由函数ReadText和WriteText实现。
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 void WriteText(FILE *); 5 void ReadText(FILE *); 6 void main() 7 { FILE *fp; 8 if((fp=fopen("myfile4.txt","w"))==NULL) 9 { printf(" open fail!!\n"); exit(0);} 10 WriteText(fp); 11 fclose(fp); 12 if((fp=fopen("myfile4.txt","r"))==NULL) 13 { printf(" open fail!!\n"); exit(0);} 14 ReadText(fp); 15 fclose(fp); 16 } 17 /**********found**********/ 18 void WriteText(FILE *fw) 19 { char str[81]; 20 printf("\nEnter string with -1 to end :\n"); 21 gets(str); 22 while(strcmp(str,"-1")!=0) { 23 /**********found**********/ 24 fputs(str,fw); fputs("\n",fw);//fputs函数向指定文件中写入一个字符串。 25 gets(str); 26 } 27 } 28 void ReadText(FILE *fr) 29 { char str[81]; 30 printf("\nRead file and output to screen :\n"); 31 fgets(str,81,fr); 32 while( !feof(fr) ) { 33 /**********found**********/ 34 printf("%s",str); 35 fgets(str,81,fr); 36 } 37 }