谁能用简单的英语举例说明printf、fprintf和sprintf之间的区别?
它在哪条小溪里?
在阅读“C语言中的文件处理”时,我真的很困惑这三个。
谁能用简单的英语举例说明printf、fprintf和sprintf之间的区别?
它在哪条小溪里?
在阅读“C语言中的文件处理”时,我真的很困惑这三个。
当前回答
其他人已经提供了详细的解释;我将通过一个非常基本的示例,将我的回答限制在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;
}
其他回答
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的工作等效。
printf
Printf用于在屏幕上执行输出。 语法= printf("控制字符串",参数); 它与文件输入/输出没有关联
流
它用来在file句柄指向的文件中执行写操作的fprintf。 语法是fprintf(文件名,“控制字符串”,参数); 它与文件输入/输出相关联
Printf(…)等价于fprintf(stdout,…)。
Fprintf用于输出到流。
Sprintf (buffer,…)用于将字符串格式化为缓冲区。
注意还有vsprintf, vfprintf和vprintf
其他人已经提供了详细的解释;我将通过一个非常基本的示例,将我的回答限制在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;
}