After a successful fgets(buffer, ...)
, it is often desirable to trim a potential End-of-Line '\n'
.
Of the following 2 methods, are there any shortcomings?
#include <stdio.h>
char buffer[100];
// Method 1
while (fgets(buffer, sizeof buffer, stdin) != NULL) {
size_t len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n')
buffer[--len] = '\0';
// use buffer
printf("\"%s\"\n", buffer);
}
// Method 2
while (fgets(buffer, sizeof buffer, stdin) != NULL) {
strtok(buffer, "\n");
// use buffer
printf("\"%s\"\n", buffer);
}
Notes:
- When reading text files from alternate file systems,
strtok(buffer, "\r\n")
looks useful. strtok()
may incur an issue with anotherstrtok()
sequence.
strtok()
sequence"? \$\endgroup\$strtok()
is not re-entrant. There is astrtok_r()
variant that is re-entrant. \$\endgroup\$strtok_r
is provided by the POSIX standard, and thatstrtok_s
is the C11 standard version. \$\endgroup\$strtok()
sequence": If code was in the middle of calling a series ofstrtok()
to perform some other tokenizing, then this use ofstrtok()
would fouls things up. That does not seem likely, but is a down side. 2) Thanks 1K 3) Did not know aboutstrtok_r()
4)strtok_s()
in in the normative "Bounds-checking interfaces" section of C11. \$\endgroup\$