c和java语言中的新行字符

时间:2014-04-05 21:42:44

标签: java c printf

现在行分隔符是系统相关的,但是在c程序中我使用'\ n'作为行分隔符,无论我是在windows还是linux中运行它都能正常工作。为什么?

在java中我们必须使用%n,因为它取决于系统,那么为什么我们在c中使用'\ n'来表示新行,而不管我们运行它的操作系统是什么?

2 个答案:

答案 0 :(得分:1)

这是C99 standard对此有何看法:

5.2.2 Character display semantics
[...]
2. Alphabetic escape sequences representing nongraphic characters in the execution
character set are intended to produce actions on display devices as follows:
[...]
\n (new line) Moves the active position to the initial position of the next line.

这意味着如果您打印" \ n",则必须将其更改为" \ r \ n"在Windows上,以满足此要求。但这仅限于显示设备,而不是文件。没有说明如何在文本文件中表示此(或任何其他空格)字符,但是:

5.2.2 Character display semantics
[...]
3. Each of these escape sequences shall produce a unique implementation-defined value
which can be stored in a single char object. The external representations in a text file
need not be identical to the internal representations, and are outside the scope of this
International Standard.

因此,您的问题的直接答案是 - 它的工作方式正如您所期望的那样,因为C标准在将\n字符打印​​到显示设备或存储在文本文件。但是,它确实准确地说明了它在打印时应该如何表现 - 它应该移动到下一行的开始

答案 1 :(得分:0)

在C程序中,您指定何时打开文件,无论是文本还是二进制文件 - 当您使用fopen打开文件时,指定一个模式字符串,如果这是b二进制文件。在读取和写入文本模式文件时,C库将自动在'\n'个字符和系统行分隔符之间进行转换。

在java中,没有类似的“文本模式”会自动为您翻译,因此要处理行分隔符,您需要在代码中明确地执行此操作。