...
| Code Block | ||
|---|---|---|
| ||
char buf[BUFSIZ + 1];
char *p;
if (fgets(buf, sizeof(buf), fp)) {
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
}
else {
/* handle error condition */
}
|
An obvious alternative is to leave room in the buffer for one more character, and when no newline is transferred, append a newline followed by a null-termination character. This approach is unsafe, because it quietly accepts an input that is not what was actually intended, with unknown consequences.
Risk Assessment
Assuming a newline character is read can result in data truncation.
...