fscanf:输入,从文件中读入到内存
fprintf:输出,从内存写入文件中
fprintf:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan", 20, 88.8 };//内存中
FILE* pf = fopen("D:\\c\\test.txt", "w");//以写的方式打开文件test.txt
if (pf == NULL)
{
perror("fopen");
return 1;
}
//格式化写入文件
fprintf(pf, "%s %d %f\n",s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
fscanf:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = {0}; //内存中
FILE* pf = fopen("D:\\c\\gitee.2022.c\\test.txt", "r"); //以读的方式打开文件
if (pf == NULL)
{
perror("fopen");
return 1;
}
//格式化读取文件,文件读入内存(输入)
fscanf(pf, "%s %d %f\n", s.name, &(s.age), &(s.score));
printf( "%s %d %f\n", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
sscanf - 从一个字符串中还原一个格式化的数据
sprintf - 把格式化的数据,存放在(转换成)一个字符串
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = {"zhangsan", 20, 99.9};
char buf[100] = {0};
sprintf(buf, "%s %d %f", s.name, s.age,s.score);
printf("%s\n", buf);
struct S tmp = { 0 };
sscanf(buf, "%s %d %f", tmp.name, &(tmp.age), &(tmp.score));
printf( "%s %d %f\n", tmp.name, tmp.age, tmp.score);
return 0;
}