我想知道使用sleep()函数时puts()和printf()函数之间的区别.
这是我的代码(C语言):
printf("hello, world");
sleep(1);
printf("Good, bye!");
Run Code Online (Sandbox Code Playgroud)
编译并运行程序后,它似乎先睡了然后打印"你好,世界好,再见!"
但是,如果使用puts()而不是printf(),它将打印"hello,world"然后睡眠,最后打印"Good,bye".
puts("hello, world");
sleep(1);
puts("Good, bye!);
Run Code Online (Sandbox Code Playgroud)
这是因为puts还输出换行符,在可以确定为交互的设备上,默认情况下会导致刷新(对于标准输出)(a).
如果您的初始printf输出结尾处有换行符,您应该会看到类似的效果:
printf("hello, world\n");
Run Code Online (Sandbox Code Playgroud)
或者如果你fflush (stdout);在sleep()电话之前.
相关部分C11是7.21.3 Files,部分/7:
在程序启动时,预定义了三个文本流,无需明确打开 - 标准输入(用于读取常规输入),标准输出(用于写入常规输出)和标准错误(用于写入诊断输出).最初打开时,标准错误流未完全缓冲; 当且仅当可以确定流不参考交互设备时,标准输入和标准输出流被完全缓冲.
这可以追溯到以下时代C89/90 4.9.3 Files:
在程序启动时,预定义了三个文本流,无需明确打开---标准输入(用于读取常规输入),标准输出(用于写入常规输出)和标准错误(用于写入诊断输出).打开时,标准错误流未完全缓冲; 当且仅当可以确定流不参考交互设备时,标准输入和标准输出流被完全缓冲.
(一):这不是很简单.对于初学者来说,这是依赖于实现的,因为标准规定构成交互设备的内容是依赖于实现的(指定行为但不影响该行为).
其次(按此处),标准仅在标准输出完全缓冲时(当设备绝对不是交互式时).无论是无缓冲还是线路缓冲的交互式设备都是一项实施决策.
这是因为缓冲 - 默认情况下,标准输出缓冲区直到每个新行.printf()不包含换行符,因此不会刷新输出.puts()包括换行符,因此刷新输出.
您可以printf()通过添加换行符来刷新:
printf("hello, world\n");
Run Code Online (Sandbox Code Playgroud)
或fflush()直接致电:
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)
有关缓冲的更多信息,请参见手册页setbuf():
Run Code Online (Sandbox Code Playgroud)The three types of buffering available are unbuffered, block buffered, and line buffered. When an output stream is unbuffered, information appears on the destination file or terminal as soon as written; when it is block buffered many characters are saved up and written as a block; when it is line buffered characters are saved up until a newline is output or input is read from any stream attached to a terminal device (typically stdin). .... If a stream refers to a terminal (as stdout normally does) it is line buffered. .... The standard error stream stderr is always unbuffered by default.