I'm trying to read in input from STDIN using read(int fd, void *buf, size_t count);
How should I handle cases when the input is EOF? Or empty string? Currently, I get a Segmentation Fault
Here is the code snippet:
int rd;
char buf[100];
rd = read(0, buf, 99);
buf[strcspn(buffer, "\n")] = 0;
Thanks
Like all other string functions, strcspn
relies on the string to be null-terminated to begin with.
If the input doesn't contain a newline, then the strcspn
function will go out of bounds due to the lack of the terminator.
You also need to handle the case when read
returns with end-of-file or error, which is indicated by it returning 0
or -1
(respectively). Just as specified in the manual (which you really should read!).
Simply add the terminator directly after the read
call at the appropriate position, but only if read
succeeds:
rd = read(STDIN_FILENO, buf, sizeof buf - 1); // sizeof buf relies on buf being an actual array and not a pointer
if (rd == -1)
{
// Error, handle it
}
else if (rd == 0)
{
// End of file, handle it
}
else
{
// Read something
buf[rd] = '\0'; // Terminate string
// Terminate a newline
buf[strcspn(buf, "\n")] = '\0'; // Truncate at newline (if any)
}