(C语言)fscanf与fprintf函数详解

目录

1 fprintf详解

1.1 向文件流中输入数据

1.2 向标准输入流写数据

2. fscanf函数详解

2.1 从文件中读取格式化数据

2.2 从标准输入流中读取格式化数据


1 fprintf详解

头文件:stdio.h

该函数和printf的参数特别像,只是多了一个参数stream,

适用于所有输出流,将格式化的数据输入到流中

1.1 向文件流中输入数据

#include <stdio.h>
struct S
{
	char name[10];
	int height;
	float grate;
}s={"xiaoming",80,65.5f};
int main()
{
	//打开文件
	FILE* pf = fopen("date.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//先文件写格式化的内容
	fprintf(pf, "%s %d %f", s.name, s.height, s.grate);
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

可见文件中的确以格式换的方式出现了结构体的数据。该函数和printf函数很像,格式化部分和prinf函数一样,只是可以控制数据到哪个流当中去。

1.2 向标准输入流写数据

#include <stdio.h>
struct S
{
	char name[10];
	int height;
	float grate;
}s={"xiaoming",80,65.5f};
int main()
{
	fprintf(stdout, "%s %d %f", s.name, s.height, s.grate);
	return 0;
}

这样结构体的数据就打印到了标准输出界面了。

2. fscanf函数详解

头文件:stdio.h

同样的fscanf和scanf很行只是多了一个stream

适用于所有输入流

将格式化的数据从流中读取出来

2.1 从文件中读取格式化数据

struct S
{
	char name[10];
	int height;
	float grate;
}s1={"xiaoming",80,65.5f},s2;
int main()
{
	//打开文件
	FILE* pf = fopen("date.txt", "w+");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//向文件写格式化的数据
	fprintf(pf, "%s,%d,%f", s1.name, s1.height, s1.grate);
	//从文件中读取格式化的数据到s2结构体
	fscanf(pf, "%s %d %f", s2.name, &s2.height, &s2.grate);
	//打印s2结构体的内容
	printf("%s %d %f", s2.name, s2.height, s2.grate);
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

2.2 从标准输入流中读取格式化数据

#include <stdio.h>
struct S
{
	char name[10];
	int age;
	float score;
}s;
int main()
{
	fscanf(stdin, "%s%*c%d%*c%f", s.name, &(s.age), &(s.score));
	printf("%s %d %f", s.name, s.age, s.score);
	return 0;
}

运行结果:

感谢观看,欢迎在评论区讨论。

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-04-25 10:12:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-25 10:12:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-25 10:12:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-25 10:12:02       18 阅读

热门阅读

  1. Edge的使用心得与深度探索

    2024-04-25 10:12:02       15 阅读
  2. tomcat到底是干嘛的?

    2024-04-25 10:12:02       13 阅读
  3. SpringBoot集成JPA及基本使用

    2024-04-25 10:12:02       17 阅读
  4. 直接扩频通信系统的Matlab实现

    2024-04-25 10:12:02       14 阅读
  5. pandas数据分析综合练习50题 - 地区房价分析

    2024-04-25 10:12:02       50 阅读
  6. NLP(7)--Embedding、池化、丢弃层

    2024-04-25 10:12:02       23 阅读
  7. 检查现有的remote repo 并换新的remote repo

    2024-04-25 10:12:02       31 阅读
  8. npm详解:Node.js的包管理器

    2024-04-25 10:12:02       17 阅读
  9. Linux 解压报错

    2024-04-25 10:12:02       11 阅读