C语言fprintf()函数和fscanf()函数的具体使用
fprintf()函数用于将格式化的数据写入文件中,它的原型为:
```c
int fprintf(FILE *stream, const char *format, ...)
```
其中,stream是指向 FILE 对象的指针,format 是一个格式化字符串,... 是可选的参数列表,用于填充格式化字符串中的占位符。
示例:
假定有一个名为 data.txt 的文件,我们要向其中写入一些数据,可使用 fprintf() 函数来实现:
```c
#include
int main() {
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
printf("没法打开文件
");
return 1;
}
int num1 = 10;
float num2 = 3.14;
char str[] = "Hello";
fprintf(file, "整数:%d
", num1);
fprintf(file, "浮点数:%f
", num2);
fprintf(file, "字符串:%s
", str);
fclose(file);
return 0;
}
```
这样,程序会将整数、浮点数和字符串依照指定的格式写入到 data.txt 文件中。
而 fscanf() 函数用于从文件中读取格式化数据,它的原型为:
```c
int fscanf(FILE *stream, const char *format, ...)
```
其中,stream 是指向 FILE 对象的指针,format 是一个格式化字符串,... 是可选的指针参数,用于接收读取的数据。
示例:
假定有一个名为 data.txt 的文件,文件内容以下:
```
整数:10
浮点数:3.14
字符串:Hello
```
现在我们想要从文件中读取这些数据,可使用 fscanf() 函数来实现:
```c
#include
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("没法打开文件
");
return 1;
}
int num1;
float num2;
char str[100];
fscanf(file, "整数:%d", &num1);
fscanf(file, "浮点数:%f", &num2);
fscanf(file, "字符串:%s", str);
printf("整数:%d
", num1);
printf("浮点数:%f
", num2);
printf("字符串:%s
", str);
fclose(file);
return 0;
}
```
这样,程序会从 data.txt 文件中读取整数、浮点数和字符串,并将它们输出到控制台上。
TOP