C & LINUX

C / LINUX fgets(3) gets(3)

Ocean_ 2022. 5. 1. 16:55

함수 기능

줄단위 입력에 사용되는 라이브러리

fgets 는 개행문자 포함 n-1개 문자 읽음.

gets 는 개행문자 만날 때까지 읽음. 개행문자는 널문자가 됨.

함수 원형

#include <stdio.h>
char *gets(char *buf);
char *fgets(char *buf, int n, FILE *fp)

리턴 값 : 성공시 buf, 파일 끝이나 에러시 NULL

함수 파라메터

buf

버퍼

 

fp

파일포인터

함수 예제

fgets1

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define BUFFER_SIZE 1024

int main(void){
    char buf[BUFFER_SIZE];
    while(fgets(buf,BUFFER_SIZE,stdin)!=NULL)
        if(fputs(buf,stdout)==EOF){
            fprintf(stderr,"standard output error\n");
            exit(1);
        }
    if(ferror(stdin)){
        fprintf(stderr,"standard input error\n");
        exit(1);
    }
    exit(0);
}

fgets2

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

#define BUFFER_MAX 256

int main(void){
    char command[BUFFER_MAX];
    char *prompt = "Prompt>>";

    while(1){
        fputs(prompt,stdout);
        if(fgets(command,sizeof(command),stdin) == NULL)
            break;
        system(command);
    }   
    fprintf(stdout,"Good bye\n");
    fflush(stdout);
    exit(0);
}

함수 결과

fgets1

fgets2

 

리눅스시스템 프로그래밍 - 홍지만 저

교재 내에 있는 예제를 바탕으로 작성한 글 입니다.