Giving EOF character from command Line

command line

I am reading character from command prompt, and checking for EOF for termination of program.
But when I am giving command Ctrl+D it is not taking as a EOF.
Kindly specify what to do for it.

Ctrl+C is working, which terminate the entire process.

Best Answer

Assuming tty "cooked" mode, ctrl-D works by terminating line input processing and sending the data already entered to the application. So if you type "abc" followed by ctrl-D those three bytes will be sent off to the application.

Now, how does an application generally determine end-of-file? EOF is assumed when a read returns 0 bytes. So you need to cause a read to return 0 bytes. If you first hit enter and then ctrl-D, first anything you typed is sent to the application together with the newline character. Then the ctrl-D causes any data you entered (i.e. nothing!) to be sent to the application, which reads 0 bytes, and assumes EOF.

If you enter anything after the enter before hitting ctrl-D then the application gets those keystrokes, and waits for more. So to generate EOF without first hitting enter, hit ctrl-D twice in a row.

So to answer your question: did you first enter any characters (besides newline) before hitting ctrl-D? If so, try it twice in succession.

This can be tested with e.g.:

$ wc -l
test123     0     1     7

(hit ctrl-D twice after the test123.)

The wc utility shows the number of lines, words and characters read. Lines is 0 because you didn't enter a newline, and test123 is one word and 7 characters long.

Related Question