简体   繁体   English

stdin是否包含回车符(\\ r)char?

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

In an SO answer I wrote this code: 在一个SO答案中,我编写了以下代码:

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). 我想知道是否有任何终端可以返回'\\r' (只要在行尾也有一个'\\n' ,则上面的代码就覆盖了)。

Does stdin ever contain '\\r' (on any platform)? stdin是否包含'\\r' (在任何平台上)? What about input redirection is stdin always working in text mode? 输入重定向如何使stdin始终在文本模式下工作?

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): 您可以从包含该字符的文件中读取,也可以执行类似的操作(在Linux和类似的操作系统下):

printf "\r" | yourProgram

Or even from a terminal program that allows escapes, such as CTRL-V CTRL-M . 甚至从允许转义的终端程序中,例如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. 但是,这不属于C语言世界中的行尾,C语言赞成使用LF方法指示行尾。 From C11 7.21.2 Streams /2 : 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. 换句话说,尽管某些系统在底层环境中使用了不同的 行结束符 ,但许多系统在C环境中进行自动转换以确保代码按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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