C语言 我什么时候应该使用 fputs 而不是 fprintf?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5690979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:24:58  来源:igfitidea点击:

When should I use fputs instead of fprintf?

c

提问by wesbos

What exactly is the difference between the two?

两者之间究竟有什么区别?

采纳答案by Sadique

fprintfdoes formatted output. That is, it reads and interprets a format string that you supply and writes to the output stream the results.

fprintf 进行格式化输出。也就是说,它读取并解释您提供的格式字符串并将结果写入输出流。

fputssimply writes the string you supply it to the indicated output stream.

fputs只是将您提供的字符串写入指定的输出流。

fputs()doesn't have to parse the input string to figure out that all you want to do is print a string.fprintf()allows you to format at the time of outputting.

fputs()不必解析输入字符串来确定您想要做的就是打印一个字符串。fprintf()允许您在输出时进行格式化。

回答by leonbloy

As have been pointed out by other commenters (and as it's obvious from the docs) the great difference is that printfallows formatting of arguments.

正如其他评论者所指出的(从文档中可以明显看出),最大的区别在于printf允许对参数进行格式化。

Perhaps you are asking if the functions are equivalent where no additional arguments are passed to printf()? Well, they are not.

也许您在问这些函数在没有传递额外参数的情况下是否等效printf()?好吧,他们不是。

   char * str;
   FILE * stream;
   ...
   fputs(str,stream);    // this is NOT the same as the following line
   fprintf(stream,str);  // this is probably wrong

The second is probably wrong, because the string argument to fprintf()is a still a formating string: if it has a '%' character it will be interpreted as a formatting specifier.

第二个可能是错误的,因为字符串参数 tofprintf()仍然是一个格式化字符串:如果它有一个 '%' 字符,它将被解释为格式化说明符。

The functionally equivalent (but less direct/efficient/nice) form would be

功能等效(但不那么直接/高效/漂亮)的形式是

   fprintf(stream,"%s", str);  

回答by slezica

Uhm... ...puts()just writes a string, while printf()has a number of formatting facilities for several types of data.

嗯... ...puts()只是写一个字符串,同时printf()有许多格式化工具用于几种类型的数据。

fputs()http://www.cplusplus.com/reference/clibrary/cstdio/fputs/

fputs()http://www.cplusplus.com/reference/clibrary/cstdio/fputs/

fprintf()http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/

fprintf()http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/

Documentation is useful! Learn to read it, and you'll have a powerful tool on your side.

文档很有用!学会阅读它,您将拥有一个强大的工具。