C stdin and CTRL+C copies previous line

85 views Asked by At

I am trying to read from stdin with fgets which is an alternate way to read apart from a file. The thought is that I should be able to write as many lines as I want and stop reading from stdin with CTRL+C is entered or any other bash terminating commands.

However the issue is that if I write a line, for instance:

mr:x:1171:1101:Mikael Rännar:/Home/staff/mr:/usr/local/bin/tcsh

and then I press ENTER to submit it and thereafter CTRL+C then it counts the line I'm terminating at the same as previous one. Here are a few examples:

mr:x:1171:1101:Mikael Rännar:/Home/staff/mr:/usr/local/bin/tcsh
<BLANKLINE>
*I PRESSED CTRL+C HERE*
Output:
Line 2: Encountered a <BLANKLINE>
Line 3: Encountered a <BLANKLINE>
1171:mr

Example 2:

mr:x:1171:1101:Mikael Rännar:/Home/staff/mr:/usr/local/bin/tcsh 
*I PRESSED CTRL+C HERE*
Output:
1171:mr
1171:mr

So my question is, how do I stop the program from copying the previous line when a terminating command is sent (CTRL+C)?

EDIT: This is my code I use to read from the stream

void readFile(FILE *fp, list *userList) {
    char line[1025];
    int lineNumber = 1;
    while (!feof(fp)) {
        user *newUser = malloc(sizeof(user));
        initializeStruct(newUser);
        fgets(line, 1025, fp);
        char *p = memchr(line, '\0', 1024);

        if (p == NULL) {
            fprintf(stderr, "Line %d: Line is too long!\n", lineNumber);
        } else {
            newUser->lineNumber = lineNumber;
            parseLine(line, newUser);
            list_insert(userList, newUser);
            lineNumber++;
        }
    }
}

When CTRL+D is pressed in bash, the fgets command uses the previous line entered.

Thanks

0

There are 0 answers