-1
        char buf[BUF_SIZE + 1];
        printf("[Enter Command]: \n");
        num_read = read(STDIN_FILENO, buf, BUF_SIZE);
        if (num_read == 5) {
            exit(0);
        }

I want to check if the user input is the string "exit" and exit the program if it is. The snippet above works but it will exit on all 4 letter strings. I only want it to exit on the string "exit".

I don't understand why the code below doesn't work:

if (strcmp("exit", buf) == 0) {
    exit(0);
}
static
  • 19
  • 2

1 Answers1

0

The strcmp() isn't working since read() is not 0-terminating the input, it's not doing string input.

Use e.g. fgets() to read a full line, then check if it starts with exit (remember that it will contain the linefeed).

unwind
  • 391,730
  • 64
  • 469
  • 606