简体   繁体   中英

Does stdin ever contain a carriage return (\r) char?

In an SO answer I wrote this code:

char fail_on_eof (int c)
{
    if (c == EOF)
        exit (EXIT_FAILURE);
    return (char) c;
}

void skip_to_next_line (void)
{
    char c;
    do
    {
        c = fail_on_eof (getchar ());
    } while (c != '\n');
}

I was wondering whether there are any terminals that may return '\\r' (which is covered by the above code as long as there is also a '\\n' at end of line).

Does stdin ever contain '\\r' (on any platform)? What about input redirection is stdin always working in text mode?

Sure, it's easy. You can read from a file containing that character, or you can do something like (under Linux and similar operating systems):

printf "\r" | yourProgram

Or even from a terminal program that allows escapes, such as CTRL-V CTRL-M .

However, that's not considered end of line in the C world, which subscribes to the LF method for indicating end of line. From C11 7.21.2 Streams /2 :

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character.

Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment.

In other words, although some systems use a different line ending character in the underlying environment, many of them do automatic translation in the C environment to ensure code acts as expected.

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