C 库 - fprintf() 函数



C 库的 fprintf() 函数用于将格式化数据写入流。它是标准 I/O 库 <stdio.h> 的一部分,允许您将数据写入文件流,而不是 `printf()` 函数,后者写入标准输出流。

语法

以下是 C 库 fprintf() 函数的语法:

int fprintf(FILE *stream, const char *format, ...);

参数

此函数接受以下参数:

  • stream : 指向 FILE 对象的指针,该对象标识要写入输出的流。
  • format : 指定输出格式的字符串。它可能包含格式说明符,这些说明符将被后续参数中指定的值替换。
  • ... : 与格式字符串中的格式说明符对应的附加参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

如果成功,`fprintf()` 函数返回写入的字符数;如果发生错误,则返回负值。

示例 1:写入文件

此示例以写入模式打开名为“output.txt”的文件,使用 `fprintf()` 将“Hello, World!”写入该文件,然后关闭该文件。

以下是 C 库 fprintf() 函数的示例。

#include <stdio.h> int main() { FILE *file_ptr; // Open file in write mode file_ptr = fopen("output.txt", "w"); if (file_ptr == NULL) { printf("Error opening file!"); return 1; } fprintf(file_ptr, "Hello, World!\n"); // Close the file fclose(file_ptr); return 0; }

输出

以上代码产生以下结果:

Hello, World!

示例 2:写入多行

此示例演示如何使用连续调用 `fprintf()` 将多行写入文件。

#include <stdio.h> int main() { FILE *file_ptr; file_ptr = fopen("output.txt", "w"); if (file_ptr == NULL) { printf("Error opening file!"); return 1; } fprintf(file_ptr, "Line 1\n"); fprintf(file_ptr, "Line 2\n"); fprintf(file_ptr, "Line 3\n"); fclose(file_ptr); return 0; }

输出

执行上述代码后,我们将得到以下结果:

Line 1
Line 2
Line 3
广告