C언어 수업정리/5월 수업정리

5월 7일 fread()/fwrite()

송시혁 2013. 5. 7. 10:56



#include
 <stdio.h>
#include <string.h>
#include <process.h>

typedef struct
{
  char name[25];
  int english, math;
  float average;
}STUDENT;

int main()
{
  STUDENT st;
  FILE *fp;
  
  if((fp=fopen ("d11-7.txt""wb"))==NULL)
  {
    printf("Can't open file d11-7.txt");
    exit(-1);
  }
  
  printf("Please type <enter key> for Name, if you finish input\n");
  printf("Enter Name: ");
  gets (st.name);
  
  while(strlen (st.name)>0)
  {
    printf("Enter English score: ");
    scanf("%d"&st.english);
    printf("Enter mayt score: ");
    scanf("%d"&st.math);
    st.average =((float)st.english + st.math)/2;
    fwrite (&st, sizeof(st), 1, fp);
    
    if(ferror (fp))
    {
      perror ("Error: ");
      fclose(fp);
      exit(-1);//return (-1);
    }

    printf("\nPlease type <enter key> for Name, if you finish input\n");
    printf("Enter Name: ");
    fflush (stdin);
    gets(st.name);
    
  }
  fclose(fp);

  if((fp= fopen ("d11-7.txt""rb"))==NULL)
  {
    printf("Can't open file d11-7.txt");
    exit(-1);
  }

  printf("\nName English Math Average\n");

  while(fread(&st, sizeof(st), 1, fp)==1)
  {
    printf("%s\t %d\t %d\t %7.2f\n", st.name, st.english, st.math, st.average);
  }
  fclose(fp);  

  return 0;
}