9

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?

2 Answers 2

13

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.

2
  • 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, 2011 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, 2011 at 10:01
11

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
2
  • Control-D twice at the end of a line does break out, without a trailing newline char...
    – Peter.O
    Aug 21, 2011 at 7:57
  • Yes, you're right. I didn't mean to imply otherwise. I edited my answer to clarify.
    – Klox
    Aug 21, 2011 at 16:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .