Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I can use cat as a very simple text editor by doing cat > foo.txt.
If I then type:

bar
baz

and then press ctrl+D, it now looks like this:

$ cat > foo.txt
bar
baz^D

with the cursor at the ^. If I then press it once more the file will get saved. However if I press anything (okay maybe not anything, but mostly anything) else, I just continue to edit the file.

Is this normal behavior?

share|improve this question

2 Answers 2

up vote 13 down vote accepted

Yes. It has to do with ^D really does: it just stops the current read(2) call.

If the program does int rdbytes = read(fd, buffer, sizeof buffer); and you press ^D inbetween, read() returns with the currently read bytes in the buffer, returning their number. The same happens on line termination; the \n at the end is always delivered.

So only a ^D at the start of a line or after another ^D has the desired effect of having read() return 0, signalizing EOF.

share|improve this answer
    
It depends on what you define a line to be (with or without a trailing \n.. but it is possible to just press ^D twice in succession, and cause an EOF condition without generating a final newline char (as pressing Enter before the ^Dwould do). –  Peter.O Aug 21 '11 at 7:03
    
Your are right, I forgot to mention that: Start of line and "just pressed ^D" are the two situations where the buffer is empty, so ^D will have read() return 0, indicating EOF. –  glglgl Aug 21 '11 at 10:01

Yes, this is normal behavior. A single Control-D normally only breaks out if it's the beginning of the line. This exits with one Control-D:

$ cat > foo.txt
bar
baz
^D
share|improve this answer
    
Control-D twice at the end of a line does break out, without a trailing newline char... –  Peter.O Aug 21 '11 at 7:57
    
Yes, you're right. I didn't mean to imply otherwise. I edited my answer to clarify. –  Klox Aug 21 '11 at 16:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.