안전한가요? fgets
은 null로 버퍼를 종료합니까? 아니면 fgets
을 호출 한 후 그리고 clean
을 호출하기 전에 20 번째 바이트를 null로 설정해야합니까?fgets()는 항상 반환하는 문자열을 null로 종료합니까?
// strip new lines
void clean(char *data)
{
while (*data)
{
if (*data == '\n' || *data == '\r') *data = '\0';
data++;
}
}
// for this, assume that the file contains 1 line no longer than 19 bytes
// buffer is freed elsewhere
char *load_latest_info(char *file)
{
FILE *f;
char *buffer = (char*) malloc(20);
if (f = fopen(file, "r"))
if (fgets(buffer, 20, f))
{
clean(buffer);
return buffer;
}
free(buffer);
return NULL;
}