谁能用简单的英语举例说明printf、fprintf和sprintf之间的区别?

它在哪条小溪里?

在阅读“C语言中的文件处理”时,我真的很困惑这三个。


当前回答

Printf(…)等价于fprintf(stdout,…)。

Fprintf用于输出到流。

Sprintf (buffer,…)用于将字符串格式化为缓冲区。

注意还有vsprintf, vfprintf和vprintf

其他回答

sprintf:将格式化的数据写入内存中的字符串,而不是stdout

sprintf的语法是:

#include <stdio.h>
int sprintf (char *string, const char *format
[,item [,item]…]);

在这里,

String指的是指向要写入数据的内存缓冲区的指针。

Format指的是指向定义格式的字符串的指针。

每个项都是一个变量或表达式,指定要写入的数据。

如果操作成功,则sprintf返回的值大于或等于零,或者换句话说,返回写入的字符数(不包括结束空字符),如果发生错误,则返回小于零的值。

printf:打印到标准输出

printf的语法是:

printf format [argument]…

sprintf()和printf()之间的唯一区别是,sprintf()将数据写入字符数组,而printf()将数据写入标准输出设备stdout。

在C语言中,“流”是一种抽象;从程序的角度来看,它只是字节的生产者(输入流)或消费者(输出流)。它可以对应于磁盘上的文件、管道、终端或打印机或tty等其他设备。FILE类型包含关于流的信息。通常,您不会直接打乱FILE对象的内容,只需将指向它的指针传递给各种I/O例程。

有三个标准流:stdin是指向标准输入流的指针,stdout是指向标准输出流的指针,stderr是指向标准错误输出流的指针。在交互会话中,这三个通常指向你的控制台,尽管你可以将它们重定向到其他文件或设备:

$ myprog < inputfile.dat > output.txt 2> errors.txt

在这个例子中,stdin现在指向inputfile.dat, stdout指向output.txt, stderr指向errors.txt。

Fprintf将格式化文本写入指定的输出流。

Printf相当于写入fprintf(stdout,…),并将格式化文本写入标准输出流当前指向的任何地方。

Sprintf将格式化文本写入char数组,而不是流。

其他人已经提供了详细的解释;我将通过一个非常基本的示例,将我的回答限制在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;
}

你也可以用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)

fprintf与流相关,其中printf是一个类似于fprintf的语句,但与流无关,也就是说fprintf是与文件相关的