简体   繁体   中英

How to detect end of file when I use fgets as an input function?

if (fgets(string, 35, stdin)==NULL)

It only works when I just use ctrl+D .

It will print

"what I want"

and exit.

But, if I type

'abc'

and don't press Enter , then ctrl+D .

It doesn't work, and continue to run again until I use ctrl+D second time.

Can you give me some idea?

This is normal behavior - when you type it after already typing some characters on the line, it allows the process to read the characters you've typed (you'll notice that you can't backspace past this point, and if you do it in eg cat the characters you typed may be echoed immediately)

The relevant Unix standard can be found here :

EOF

Special character on input, which is recognized if the ICANON flag is set. When received, all the bytes waiting to be read are immediately passed to the process without waiting for a < newline >, and the EOF is discarded. Thus, if there are no bytes waiting (that is, the EOF occurred at the beginning of a line), a byte count of zero shall be returned from the read(), representing an end-of-file indication. If ICANON is set, the EOF character shall be discarded when processed.

Basically, ctrl-D in the middle of the line isn't "really" the end of the file, and there's no reason to expect to detect it. If you want to end standard input without a final newline, just press ctrl-D twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM