문제
5명의 학생에 대한 정보를 파일에 저장하는 C 프로그램을 작성하고 fread() 및 fwrite()를 사용하여 출력하십시오.
해결책
fread() 함수 한 번에 전체 레코드를 읽습니다.
구문
fread( & structure variable, size of (structure variable), no of records, file pointer);
예시
struct emp{
int eno;
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp); fwrite() 함수 한 번에 전체 레코드를 씁니다.
구문
fwrite( & structure variable , size of structure variable, no of records, file pointer);
예시
struct emp{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp); 프로그램
#include<stdio.h>
struct student{
int sno;
char sname [30];
float marks;
char temp;
};
main ( ){
struct student s[60];
int i;
FILE *fp;
fp = fopen ("student1.txt", "w");
for (i=0; i<2; i++){
printf ("enter details of student %d\n", i+1);
printf("student number:");
scanf("%d",&s[i].sno);
scanf("%c",&s[i].temp);
printf("student name:");
gets(s[i].sname);
printf("student marks:");
scanf("%f",&s[i].marks);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fclose (fp);
fp = fopen ("student1.txt", "r");
for (i=0; i<2; i++){
printf ("details of student %d are\n", i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf("student number = %d\n", s[i]. sno);
printf("student name = %s\n", s[i]. sname);
printf("marks = %f\n", s[i]. marks);
}
fclose(fp);
getch( );
} 출력
enter details of student 1 student number:1 student name:pinky student marks:56 enter details of student 2 student number:2 student name:rosy student marks:87 details of student 1 are student number = 1 student name = pinky marks = 56.000000 details of student 2 are student number = 2 student name = rosy marks = 87.000000