1. 程式人生 >實用技巧 >其它 >95

95


技術標籤:C

95 date:2021.2.18

95


要點: 檔案指標

詳細程式碼如下:

#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);
   }
}


95


要點: 結構體

詳細程式碼如下:

#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);
}