C fprintf: Write Data to File Example
In C language, you can use the standard library function fprintf to write data to a file. The prototype of the fprintf function is as follows:
int fprintf(FILE *stream, const char *format, ...)
In this case, stream refers to a pointer to a file, format is a formatting string, and the following parameters are the data to be written. Here is an example:
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "w"); // 打开文件,以写入模式打开
if (file == NULL) {
printf("文件打开失败\n");
return 1;
}
int n = 10;
float f = 3.1415;
char str[] = "Hello";
fprintf(file, "%d %.2f %s", n, f, str); // 向文件写入数据
fclose(file); // 关闭文件
return 0;
}
In the example above, we first use the fopen function to open a file named data.txt in write mode. If the file is successfully opened, it returns a pointer to the file, otherwise it returns NULL. Then, we use the fprintf function to write data to the file, with the format string “%d %.2f %s” specifying the format of the data being written. Finally, we use the fclose function to close the file.
Certainly, before writing to a file, we need to make sure that the file is properly opened. After writing the data, we also need to close the file to release file resources.