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

它在哪条小溪里?

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


当前回答

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

其他回答

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

printf

Printf用于在屏幕上执行输出。 语法= printf("控制字符串",参数); 它与文件输入/输出没有关联

它用来在file句柄指向的文件中执行写操作的fprintf。 语法是fprintf(文件名,“控制字符串”,参数); 它与文件输入/输出相关联

Printf输出到标准输出流(stdout)

fprintf转到文件句柄(file *)

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;
}

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。