温馨提示×

C语言fprintf()函数和fscanf()函数的具体使用

小云
98
2023-08-16 15:59:06
栏目: 编程语言

fprintf()函数用于将格式化的数据写入文件中,它的原型为:

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

其中,stream是指向 FILE 对象的指针,format 是一个格式化字符串,… 是可选的参数列表,用于填充格式化字符串中的占位符。

示例:

假设有一个名为 data.txt 的文件,我们要向其中写入一些数据,可以使用 fprintf() 函数来实现:

#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
int num1 = 10;
float num2 = 3.14;
char str[] = "Hello";
fprintf(file, "整数:%d\n", num1);
fprintf(file, "浮点数:%f\n", num2);
fprintf(file, "字符串:%s\n", str);
fclose(file);
return 0;
}

这样,程序会将整数、浮点数和字符串按照指定的格式写入到 data.txt 文件中。

而 fscanf() 函数用于从文件中读取格式化数据,它的原型为:

int fscanf(FILE *stream, const char *format, ...)

其中,stream 是指向 FILE 对象的指针,format 是一个格式化字符串,… 是可选的指针参数,用于接收读取的数据。

示例:

假设有一个名为 data.txt 的文件,文件内容如下:

整数:10
浮点数:3.14
字符串:Hello

现在我们想要从文件中读取这些数据,可以使用 fscanf() 函数来实现:

#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
int num1;
float num2;
char str[100];
fscanf(file, "整数:%d", &num1);
fscanf(file, "浮点数:%f", &num2);
fscanf(file, "字符串:%s", str);
printf("整数:%d\n", num1);
printf("浮点数:%f\n", num2);
printf("字符串:%s\n", str);
fclose(file);
return 0;
}

这样,程序会从 data.txt 文件中读取整数、浮点数和字符串,并将它们输出到控制台上。

0