이 포스팅은 한국기술교육대학교 김덕수 교수님의 시스템 프로그래밍 (CSE 232)를 참고하여 작성되었습니다.
표준 파일 입출력에는 다음 4가지가 있다.
(1) Character IO
(2) String IO
(3) Binary IO
(4) Formatted IO
이번 포스팅에서는 (3), (4)에 대해서 다루겠다.
문자인 경우 '아스키 코드' 로 변환되어 저장된다.
파이너리 파일은 메모리에 있는 이진수 데이터가 그대로 저장된다.
#1 Binary IO
FILE *fopen(const char *filename, const char *mode);
파일을 읽을 때 mode인자에 binary인자를 포함하여 읽으면 된다.
Binary IO Read & Write, fread(3), fwrite(3)
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
// 크기가 size인 item을 count 개수 만큼 stream에서 읽어 ptr에 저장
size_t fwrite(const void *ptr, size_t size, size_t count,
FILE *stream);
// 크기가 size인 item을 count 개수 만큼 ptr에서 읽어 stream에 출력
ptr : Pointer to buffer
size : size of an item
count : number of items to read/write
stream
Return : read/write 한 item의 수 | EOF : 파일 끝
Binary IO - fwrite()
#include <stdio.h> #include <stdlib.h>
int main(void)
{
char *fileName = "binary.bin";
int data[5] = {10, 20, 30, 40, 50};
FILE *fp = NULL;
if (!(fp = fopen(fileName, "wb")))
{
fprintf(stderr, "Fail to open the file - %s\n", fileName);
exit(1);
}
size_t i = fwrite(data, sizeof(int), 5, fp);
printf("Success to write %d object(s).\n", (int)i);
fclose(fp);
return 0;
}
Binary IO - fread()
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int buf[5] = {0};
FILE *fp = fopen("binary.bin", "rb");
if (!fp)
{
fprintf(stderr, "Fail to open the file - %s\n", "binary.bin");
exit(1);
}
size_t i = fread(buf, sizeof(int), 5, fp);
printf("Success to read %d object(s).\n", (int)i);
for (int i = 0; i < 5; i++)
printf("%d ", buf[i]);
fclose(fp);
return 0;
}
Ascii (Text) File VS Binary File
Ascii (text) file (텍스트 파일)
- 사람이 바로 읽을 수 있음
- 데이터 저장 및 사용 시, 문자로 (or 문제에서)변환 과정이 필요함
많은 양의 데이터 처리에 비효율 적
동일한 데이터를 저장하는 이진 파일대비 많은 공간을 요구
Binary file (이진 파일)
- 컴퓨터가 바로 사용할 수 있는 형태 (메모리에 저장된 형태 그대로 저장)
별도의 변화 과정 없이 읽기/쓰기 가능
데이터 처리에 효율적이며, 저장 공간을 효율적으로 사용할 수 있음
- 사람이 읽을 수 없는 형태 > 데이터 교환 시 약속(Protocol)이 필요 함
김덕수 교수님께서 강의중 위 Binary IO를 익힐 수 있는 예제를 제공해 주셨다.
하단의 Github 링크를 참고하여 복습을 해보다.
https://github.com/bluekds/SystemProgramming/blob/main/Lecture3/studentDB/studentDB.c
GitHub - bluekds/SystemProgramming
Contribute to bluekds/SystemProgramming development by creating an account on GitHub.
github.com
#2 Formatted IO
#include <stdio.h>
int scanf(const char *format, argument-list);
int fscanf (FILE *stream, const char *format, argument-list);
int printf(const char *format, argument-list);
int fprintf(FILE *stream, const char *format, argument-list);
format : 입출력 형식
stream
Return : 입출력 한 문자 수 | 음수 : error
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int ID;
char name[8];
float score;
} Student;
int fileOpen(FILE** _fp, char* _fileName, char* _mode) {
*_fp = fopen(_fileName, _mode);
if (!*_fp) {
printf("Fail to open - %s\n", _fileName);
return -1;
}
return 0;
}
int main(void) {
Student info = { 0 };
char* fileName = "StudentList.txt";
FILE* fp = NULL;
if (fileOpen(&fp, fileName, "a") < 0)
exit(1);
while(1) { // Get and store the student info
printf("Enter ID Name Score (Exit: -1): ");
scanf("%d", &info.ID);
if (info.ID < 0)
break;
scanf("%s %f", (char*)&info.name, &info.score); getchar();
fprintf(fp, "%d %s %.1f\n", info.ID, info.name, info.score);
}
fclose(fp);
if (fileOpen(&fp, fileName, "r") < 0)
exit(1);
int numStudent = 0;
float sum = 0;
while (!feof(fp)) {
fscanf(fp, "%d %s %f\n", &info.ID, (char*)&info.name, &info.score);
sum += info.score;
numStudent++;
}
printf("%d students, Average = %.2f\n", numStudent, sum / numStudent);
fclose(fp);
}
#3 Synchronizing with the disk
low-level IO 에서도 page-back write를 위해서 fsync를 사용했다.
standard IO에서 사용하는 함수는 fflush 이다.
#include <stdio.h>
int fflush(FILE *stream);
Stream
Return : 0 = success | -1 = error
#4 Controlling buffering
#include <stdio.h>
int setvbuf(FILE *stream, char *buf, int type, size_t size);
Standard IO는 3가지 buffering mode 지원
(1) Unbuffered (_IONBF)
(2) Line-buffered (_IOLBF) (e.g., stdout, stdin)
(3) Block-buffered (_IOFBF)
긴 글 읽어주셔서 감사드립니다.
22.12.14
'TIL (Today I Learned) > 컴퓨터 시스템(CS)' 카테고리의 다른 글
[CS] Process vs Thread (0) | 2022.12.15 |
---|---|
[CS] 표준 입출력, File offset & File pointerIO #5 (0) | 2022.12.14 |
[CS] 표준 입출력, Standard IO #3 (1) | 2022.12.14 |
[CS] 표준 입출력, Standard IO #2 (0) | 2022.12.14 |
[CS] 표준 입출력, Buffered IO #1 (0) | 2022.12.14 |
댓글