realUser404
realUser404

Reputation: 2231

EOF from standard input is displayed in standard output

I am doing a few tests with reading from standard input and writing in standard output, and something is really bothering me.

When I try to write a single character followed by a \n, the "D" from the EOF (I presume) is printing after the character.

Here is what happens in the terminal :

 >./myprog
 sometext I enter
 "Ctrl + D"
 jD
 j
 >

and here is the code :

#define BUF_SIZE 4096

void    read_std_in()
{
    int     ret;
    char    buf[BUF_SIZE + 1];

    while ((ret = read(0, buf, BUF_SIZE)))
    {
        buf[ret] = '\0';
        // Concatenating buffer with some other string, not important here.
    }
    write(1, "j", 1);
    write(1, "\n", 1);
    write(1, "j", 1);
    write(1, "\n", 1);
}

As you can see, the first "j" gets a "D" from nowhere.

If I try displaying more than 1 character for the forst line, the problem doesn't appear :

 >./myprog
 sometext I enter
 "Ctrl + D"
 jj
 j
 >

And if I put no char (just \n) I get :

 >./myprog
 sometext I enter
 "Ctrl + D"
 ^D
 j
 >

How can I avoid this behaviour?

Upvotes: 2

Views: 73

Answers (1)

r3mainer
r3mainer

Reputation: 24567

I'm getting the same behaviour in OS X/Darwin.

It looks like ^D is being echoed to the console when you hit CtrlD, but without advancing the text cursor. As a result, the first j is being placed on top of the ^ character. (You can verify this by changing the first write(1, "j", 1); to write(1, "\33[2Cj", 5);, which moves the cursor two places to the right before printing j.)

I don't think there is any simple way to prevent ^D from appearing, so you could just ignore it. The D isn't added to your input, so it won't cause any problems with the operation of your software.

Alternatively, if you pipe the input to your program, then the problem will go away:

./myprog <<<"some text"

Upvotes: 5

Related Questions