Monday, October 31, 2022

[FIXED] How do you detect ctrl+D in C?

Issue

So I read in a line using fgets

line = fgets(l, BUFSIZ, stdin);

And I from what I understand control+d is EOF so I tried

if(line[0] == EOF)
     continue;

to get back to the top of the loop. But this led to segfaults... Is there another way?


Solution

Since the machine generates EOF on Ctrl + D, you should be checking fgets() for NULL, as fgets() is obliged to return NULL on end of file.

line = fgets(l, BUFFSIZ, stdin)
if (line == NULL)
    continue;

In your code, you are trying to dereference a pointer that's NULL leading to segfault.



Answered By - Arjun Sreedharan
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.