fgets
The fgets
function is useful when you want to read one line (with a maximum length) at a time. It has the following prototype:
char * fgets(char * str, int size, FILE * stream);
This function takes three arguments:
str
) where the characters read from the file will be stored. For example, fgets
will write the data into str[0]
, str[1]
, str[2]
, and so on.str
. This argument specifies the maximum number of characters to read, including the null terminator.fopen
).Return Value:
str
. In this case, the data in str
is null-terminated.NULL
. To distinguish between an end-of-file condition and an error, you can use the feof
and/or ferror
functions.This is a good time to mention that you should never use the gets
function. While gets
is similar to fgets
, it does not take an argument specifying the size of the array. Therefore, it continues reading data until it reaches a newline, even if it writes past the array's bounds, leading to buffer overflow vulnerabilities. This lack of boundary checking poses a significant security risk, making gets
unsafe.
fgets
함수는 한 번에 한 줄(최대 길이를 지정할 수 있음)을 읽을 때 유용합니다. 다음과 같은 프로토타입을 가지고 있습니다:
char * fgets(char * str, int size, FILE * stream);
이 함수는 세 가지 인수를 받습니다:
str
)에 대한 포인터입니다. 예를 들어, fgets
는 데이터를 str[0]
, str[1]
, str[2]
등에 기록합니다.str
의 크기입니다. 이 인수는 null 종결자를 포함한 최대 읽기 문자를 지정합니다.fopen
으로 반환된 파일 포인터 등).반환 값: