본문 바로가기
TIL (Today I Learned)/컴퓨터 시스템(CS)

[CS] 표준 입출력, Standard IO #3

by 둥굴프 2022. 12. 14.
이 포스팅은 한국기술교육대학교 김덕수 교수님의 시스템 프로그래밍 (CSE 232)를 참고하여 작성되었습니다.

 

표준 파일 입출력에는 다음 4가지가 있다.

(1) Character IO

(2) String IO

(3) Binary IO

(4) Formatted IO

 

이번 포스팅에서는 (1), (2)에 대해서 다루겠다.

 

 

#1 Character-based reading, fgetc(3)

#include <stdio.h>
int fgetc(FILE *stream);
int getc(FILE *stream); // macro
int getchar(void); // = getc(stdin)

stream : File operation을 수행할 stream

c (character) : 쓰려는 문자

Return : 읽은/기록한 문자 | EOF(-1) : error

 

getc는 macro형태로 구현되어있다.

그렇기 때문에 함수를 호출하는 오버헤드가 빠지게 된다.

하지만, 인자에 수식이 들어가면 안 된다.

 

getchar는 키보드로 받는 input 하나를 가져온다.

 

 

#2 Character-based writing, fputc(3)

#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c); // putc(stdout)

stream : File operation을 수행할 stream

c (character) : 쓰려는 문자

Return : 읽은/기록한 문자 | EOF(-1) : error

 

putchar는 모니터에 쓰겠다.

 

 

Character-based IO

#include <stdlib.h>
#include <stdio.h>

int main(void) {
    FILE *rfp, *wfp;
    int c;
 if ((rfp = fopen("hello.txt", "r")) == NULL) {
        perror("fopen: hello.txt");
        exit(1);
    }

    if ((wfp = fopen("hello.out", "w")) == NULL) {
        perror("fopen: hello.out");
        exit(1);
    }

    while ((c = fgetc(rfp)) != EOF) {
        fputc(c, wfp);
    }

    fclose(rfp);
    fclose(wfp);

    return 0;
}

 

#3 String-based reading, fgets(3)

#include <stdio.h>
char *gets(char *buffer);
	// get from stdin (buffer size에 대한 고여 없음 = 보안문제)
char *fgets (char *string, int n, FILE *stream);
	// Stream에서 (n-1)개의 문자를 읽어서 s에 저장
	// \n 또는 EOF를 만나면 해당 지점에서만 읽어옴

s (string) : 읽은 문자열을 저장할 buffer

n : buffer의 크기

stream : File operation을 수행할 stream

Return : Buffer의 시작 주소 | NULL : 읽을 것이 없음

 

 

#4 String-based writing, fputs(3)

#include <stdio.h>
int puts(const char *string); // put to stdout (with \n)
int fputs(const char *string, FILE *stream);
	// s를 stream에 출력 (\n 추가 하지 않음)

s (string) : 기록할 문자열을 저장할 buffer

stream : File operation을 수행할 stream

Return :양수 = success, 음수 = error

 

 

String-based IO

#include <stdlib.h>
#include <stdio.h>

int main(void) {
    FILE *rfp, *wfp;
    char buf[BUFSIZ]; // BUFSIZ is defined in the stdio.h
    printf("BUFSIZ = %d\n", BUFSIZ);

    if ((rfp = fopen("hello.txt", "r")) == NULL) {
        perror("fopen: hello.txt");
        exit(1);
    }

    if ((wfp = fopen("hello.out", "a")) == NULL) {
        perror("fopen: hello.out");
        exit(1);
    }

    while (fgets(buf, BUFSIZ, rfp) != NULL) {
        fputs(buf, wfp);
    }

    fclose(rfp);
    fclose(wfp);

    return 0;
}

 

 

 

긴 글 읽어주셔서 감사드립니다.

22.12.14

댓글