LibC: cleanup and fix fgets

My quick fix for fgets wrote non-nullterminated newline if size was
one.

POSIX doesn't specify what happens if size == 0, so I do the same as
glibc and return NULL without setting errno.
This commit is contained in:
Bananymous 2023-12-05 10:00:43 +02:00
parent 82cb2ea20b
commit 894065a67e
1 changed files with 13 additions and 24 deletions

View File

@ -135,37 +135,26 @@ int fgetpos(FILE* file, fpos_t* pos)
char* fgets(char* str, int size, FILE* file) char* fgets(char* str, int size, FILE* file)
{ {
if (size == 1) if (size == 0)
str[0] = '\n';
if (size <= 1)
return str;
int c = fgetc(file);
if (c == EOF)
return nullptr; return nullptr;
str[0] = c; int i = 0;
if (str[0] == '\n') for (; i < size - 1; i++)
{ {
str[1] = '\0'; char c = fgetc(file);
return str; if (c == EOF)
}
for (int i = 1; i < size - 1; i++)
{
str[i] = fgetc(file);
if (str[i] == EOF)
{ {
str[i] = '\0'; if (i == 0)
return str; return nullptr;
break;
} }
if (str[i] == '\n') str[i] = c;
if (c == '\n')
{ {
str[i + 1] = '\0'; i++;
return str; break;
} }
} }
str[i] = '\0';
str[size - 1] = '\0';
return str; return str;
} }