在 C 语言 中,scanf 函数可以将我们键盘输入的数据保存到 变量 中,同时,fscanf 函数 可以实现按照特定的格式将数据写从 文件 读取到内存中。
int fscanf(FILE *fp, char * format, ...);
参数 | 描述 |
---|---|
fp | 文件指针。 |
format | 格式控制字符串。 |
… | 参数列表。 |
fscanf() 返回参数列表中被成功赋值的参数个数。
fscanf 函数在 stdio.h 的头文件里面。
使用 fprintf 写入文件,使用 fscanf 函数读取文件
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char name[10];
int age;
float score;
};
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
// 定义结构体
struct Student students[3];
// 输入学生信息
int i = 0;
for(i = 0; i < 3; i++)
{
printf("Please input student %d name, age and score: ", i+1);
scanf("%s", students[i].name);
scanf("%d", &students[i].age);
scanf("%f", &students[i].score);
}
// 打开文件
FILE *fp = NULL;
if ( (fp = fopen("c:\\haicoder.txt", "wt+")) == NULL )
{
puts("Open file failed\n");
return;
}
// 写入文件
i = 0;
for(i = 0; i < 3; i++)
{
fscanf(fp, "%s %d %f", students[i].name, students[i].age, students[i].score);
}
puts("Write file success");
// 读取文件
struct Student retStudents[3];
i = 0;
for(i = 0; i < 3; i++)
{
fprintf(fp, "%s %d %f", students[i].name, &students[i].age, &students[i].score);
printf("Read Student %d Name: %s, Age: %d, Score: %f\n", i+1, students[i].name, students[i].age, students[i].score);
}
fclose(fp);
return 0;
}
程序运行后,控制台输出如下:
我们使用了 fprintf 函数将 结构体 写入了文件,接着,使用了 fscanf 函数从文件中读取出了结构体的内容。
在 C 语言中,scanf 函数可以将我们键盘输入的数据保存到变量中,同时,fscanf 函数可以实现按照特定的格式将数据写从文件读取到内存中。