프로그램이 꺼진 이후에도 데이터를 저장하기 위해 파일 입출력이 필요함.
파일 입출력 변수는 FILE형식의 포인트 변수로 선언한다.
파일을 열때는 fopen() 함수 사용
파일을 닫을때는 fclose() 함수 사용FILE *fp; fp = fopen(파일 경로, 접근 방식); fclose(fp);
파일 경로와 접근 방식을 설정할 수 있다.
접근 방식
fprint(파일 포인터, 서식, 형식지정자);
fscanf(파일 포인터, 서식, 형식지정자);
파일을 열 때에는 파일 포인터가 사용되며 이는 동적으로 할당된 것이다. 파일 처리 이후에 파일을 닫지 않으면 메모리 누수가 발생한다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void){
char s[20] = "hello world";
FILE *fp;
fp = fopen("temp.txt","w");
fprintf(fp,"%s\n",s);
fclose(fp);
return 0;
}
디버그를 하면 아래와 같은 창이 뜬다.
그리고 이 예제파일이 있는 위치로 가보면 temp.txt라는 파일이 생성되어있는 것을 알 수 있다.
위와 같이 우리가 fprintf에 쓴 내용이 입력되었다.
위의 내용을 input.txt파일로 만든 후 진행한다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>//동적 메모리 할당하기 때문에 사용
#include <string.h>
typedef struct {
char name[20];
int score;
} Student;
int main(void){
int n, sum=0;
FILE *fp;
fp = fopen("input.txt","r");
fscanf(fp,"%d",,&n);
Student *students = (Student*)malloc(sizeof(Student)*n);
for(int i=0; i < n; i++){
fscanf(fp, "%s %d" , &((students +i)->name), &((students + i)->score));
printf("이름: %s, 성적: %d\n",(students +i)->name,(studnets+i)->score);
}
system("pause");
return 0;
}
실행하면
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char name[20]'
int score;
}Student;
int main (void){
int n,sum=0;
FILE *fp;
fp = fopen("input.txt","r");
fscanf(fp,"%d", &n);
Student *students = (Student*)malloc(sizeof(Student) *n);
for(int i=0; i<n;i++){
fscanf(fp,"%s %d",&((studnets +i)->name),&((students + i)->score));
}
for(int i=0; i<n;i++){
sum += (studnets +i)->score;
}
free(students);
fclose(fp);
printf("점수 평군: %.2f\n", (double)sum /n);
system("pause");
return 0;
}