ctrl-d appends characters to output

Montgomery-Smith, Stephen stephen at missouri.edu
Sat Jan 17 20:17:20 UTC 2015


On 01/17/2015 11:59 AM, less xss wrote:
> I've searched around quite a bit with no luck on this matter. I currently
> have an issue where I send EOF (ctrl-d) to some simple K&R2 exercises and
> the terminal returns the D character appended to my data when EOF is sent.
> I wish to prevent any and all extra characters from being appended and I
> would also like to understand why it's happening. The following code
> is an example exercise from K&R2 that yield said problem.
> 
> #include <stdio.h>
> 
> int main() {
>     double nc;
> 
>     for (nc = 0; getchar() != EOF; ++nc) {
>         ; /* syntactic null statement */
>     }
> 
>     printf("%.0f\n", nc);
> }
> 
> $ ./a.out
> 0D
> $

I did a bit of experimenting with this issue.  First, I cannot reproduce
it on my Linux box.  Second, this simpler program does the same thing:

#include <stdio.h>

int main() {

    while (getchar() != EOF) {
        ; /* syntactic null statement */
    }

    printf("\n");
}

In this case I get:

% ./a.out
^D
%

However, if I remove that last printf statement, then no ^D is displayed.

Considering the inconsistent nature of when this ^D appears, I would
prefer to call it a bug than a feature.  But it must have been put there
by design.


More information about the freebsd-hackers mailing list