谁能用简单的英语举例说明printf、fprintf和sprintf之间的区别?
它在哪条小溪里?
在阅读“C语言中的文件处理”时,我真的很困惑这三个。
谁能用简单的英语举例说明printf、fprintf和sprintf之间的区别?
它在哪条小溪里?
在阅读“C语言中的文件处理”时,我真的很困惑这三个。
当前回答
Printf输出到标准输出流(stdout)
fprintf转到文件句柄(file *)
Sprintf进入您分配的缓冲区。(char *)
其他回答
Printf(…)等价于fprintf(stdout,…)。
Fprintf用于输出到流。
Sprintf (buffer,…)用于将字符串格式化为缓冲区。
注意还有vsprintf, vfprintf和vprintf
Printf输出到标准输出流(stdout)
fprintf转到文件句柄(file *)
Sprintf进入您分配的缓冲区。(char *)
printf(const char *format, ...) is used to print the data onto the standard output which is often a computer monitor. sprintf(char *str, const char *format, ...) is like printf. Instead of displaying the formated string on the standard output i.e. a monitor, it stores the formated data in a string pointed to by the char pointer (the very first parameter). The string location is the only difference between printf and sprint syntax. fprintf(FILE *stream, const char *format, ...) is like printf again. Here, instead of displaying the data on the monitor, or saving it in some string, the formatted data is saved on a file which is pointed to by the file pointer which is used as the first parameter to fprintf. The file pointer is the only addition to the syntax of printf.
如果在fprintf中使用stdout文件作为第一个参数,那么它的工作将被认为与printf的工作等效。
你也可以用vsnprintf()函数做一些非常有用的事情:
$ cat test.cc
#include <exception>
#include <stdarg.h>
#include <stdio.h>
struct exception_fmt : std::exception
{
exception_fmt(char const* fmt, ...) __attribute__ ((format(printf,2,3)));
char const* what() const throw() { return msg_; }
char msg_[0x800];
};
exception_fmt::exception_fmt(char const* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(msg_, sizeof msg_, fmt, ap);
va_end(ap);
}
int main(int ac, char** av)
{
throw exception_fmt("%s: bad number of arguments %d", *av, ac);
}
$ g++ -Wall -o test test.cc
$ ./test
terminate called after throwing an instance of 'exception_fmt'
what(): ./test: bad number of arguments 1
Aborted (core dumped)
其他人已经提供了详细的解释;我将通过一个非常基本的示例,将我的回答限制在print与sprintf的实际讨论中。
假设您希望程序同时输出当前行号和文件名。具体来说,您希望:(i)将其打印在屏幕上,(ii)将其保存在变量中,以备将来使用。您可以对(i)使用printf,对(ii)使用sprintf。以下是代码。
/* saves file name and current line in a string and prints it on the screen*/
#include <stdio.h>
int main(void) {
/* note the use of a marco to save the line nr. */
int line_n= __LINE__;
/* note the use of a marco to save the file name */
char file_name[]= __FILE__;
/* Some text you wish to print/save */
char line[] = "Line ";
char file[]= " of file ";
char my_str[100];
/* expand everything and save it in my_str for future use */
sprintf(my_str, "%s%d%s%s", line, line_n, file, file_name);
/* or just print it out on the screen */
printf("%s", my_str);
return 0;
}