fgets() returns NULL if it hits EOF before reading anything. I added a boolean return parameter (a pointer that can optionally be NULL) to return whether or not a newline was found and removed. sz must be > 1
Code:
#include <stdio.h>
#include <string.h>
char *xfgets(char *line, size_t sz, FILE *fin, int *nl_found) {
int c;
if (nl_found) *nl_found = 0;
if (sz < 2 || (c = fgetc(fin)) == EOF)
return NULL;
do {
if (c == '\n') {
if (nl_found) *nl_found = 1;
break;
}
else
*line++ = c;
}while (--sz > 1 && (c = fgetc(fin)) != EOF);
*line = '\0';
return line;
}
int main() {
char line[2]; // small for testing
int nl_found = 0;
while (xfgets(line, sizeof line, stdin, &nl_found)) {
printf("%s", line);
if (nl_found) putchar('\n');
}
return 0;
}