1. 程式人生 > 其它 >C語言:檔案(5)fscanf和fprintf

C語言:檔案(5)fscanf和fprintf

技術標籤:C語言應用C語言進階c語言

格式化輸入函式 fscanf
格式化輸出函式 fprintf

#include<stdio.h>
struct S
{
	int a;
	float b;
	char c[20];
};

int main()
{
	struct S s = { 0 };
	fscanf(stdin, "%d %f %s", &s.a, &s.b, &s.c);//從鍵盤上接收
	fprintf(stdout, "%d %g %s", s.a, s.b, s.c);//列印到螢幕上
	return 0;
}

fscanf的使用

struct S
{
	int a;
	float b;
	char c[20];
};
int main()
{
	struct S s = { 0 };
	FILE* f = fopen("text.txt", "r");
	if (f==NULL)
	{
		return 0;
	}
	//從檔案f中讀取資料以"%d %f %s"的格式,分別寫進到s.a, s.b, s.c中。
	fscanf(f, "%d %f %s", &s.a, &s.b, s.c);
	printf(
"%d %g %s", s.a, s.b, s.c); fclose(f); f = NULL; return 0; }

fprintf的使用

struct S
{
	int a;
	float b;
	char c[20];
};
int main()
{
	struct S s = { 1,1.34,"asdf" };
	FILE* f = fopen("text.txt", "w");
	if (f==NULL)
	{
		return 0;
	}
	//將s.a, s.b, s.c的資料以"%d %g %s"的格式輸入到f檔案中。
fprintf(f,"%d %g %s", s.a, s.b, s.c); fclose(f); f = NULL; return 0; }

在這裡插入圖片描述