哪个更好 - printf或fprintf

Lio*_*ior 7 c printf output

我知道这两个函数都可以用来输出到控制台.
我读了这个问题,但没有人告诉我在输出到控制台时更喜欢使用哪个.那么哪个功能更好,有什么重大差异吗?

Dan*_*her 12

引用标准(n1570中的7.21.6.3):

printf函数等同于fprintf在参数stdout之前插入的参数printf.

因此printf在打印到控制台时更方便,否则没有区别.但是fprintf,如果要更改输出目标,则更容易修改.

  • 这意味着它不是一个符合标准的实现,不是吗? (2认同)

Wil*_*ris 7

每个进程都有一个输入流,命名stdin和两个输出流,stdoutstderr.这些输出流都连接到您的终端,因此以下命令将打印"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流重定向lsotherfile.您可以通过查看以下内容来查看重定向的输出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(控制你的终端的程序)如何完成.