Dan*_*her 12
引用标准(n1570中的7.21.6.3):
该
printf函数等同于fprintf在参数stdout之前插入的参数printf.
因此printf在打印到控制台时更方便,否则没有区别.但是fprintf,如果要更改输出目标,则更容易修改.
每个进程都有一个输入流,命名stdin和两个输出流,stdout和stderr.这些输出流都连接到您的终端,因此以下命令将打印"hello"行到您的终端:
printf("hello\n");
fprintf(stdout, "hello\n");
fprintf(stderr, "hello\n");
Run Code Online (Sandbox Code Playgroud)
前两个完全相同,第一个只是更短更方便.第一种是最常用的.
第三个不同之处在于发送到的内容在stderr逻辑上与发送的内容是分开的stdout.它通常用于您希望用户看到的错误消息.库函数将perror其错误消息打印到stderr.
stderr逻辑上分离的流的重要性在于其内容可以与之分离stdout.例如,假设我们使用该命令ls -l列出文件.
$ touch myfile
$ ls -l myfile
-rw-r--r-- 1 wrm staff 0 6 Nov 20:44 myfile
Run Code Online (Sandbox Code Playgroud)
现在,如果我们将输出重定向ls到另一个文件,我们会看到以下内容:
$ ls -l myfile > otherfile
$
Run Code Online (Sandbox Code Playgroud)
没有打印输出,因为>将进程stdout流重定向ls到otherfile.您可以通过查看以下内容来查看重定向的输出otherfile:
$ cat otherfile
-rw-r--r-- 1 wrm staff 0 6 Nov 20:44 myfile
$
Run Code Online (Sandbox Code Playgroud)
但是>没有重定向stderr流.您可以通过删除myfile并重新运行重定向ls -l命令来测试它:
$ rm myfile
$ ls -l myfile > otherfile
ls: myfile: No such file or directory
$
Run Code Online (Sandbox Code Playgroud)
所以在这里你可以看到虽然stdout被重定向到otherfile,stderr但没有被重定向,所以它的内容出现在终端上.另请注意,otherfile现在是空的,因为ls命令找不到myfile,因此没有任何内容可以发送stdout.
它也可以重定向stderr,但它取决于你的shell(控制你的终端的程序)如何完成.
| 归档时间: |
|
| 查看次数: |
13852 次 |
| 最近记录: |