输出不同类型数据到文件
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
int num;
char name[10];
char sex;
};
int main()
{
//打开文件
FILE* fp;
fp = fopen("test.dat", "w");
if (fp == NULL)
{
perror("fopen");
exit(0);
}
//输出不同类型数据到文件
struct Stu s = { 1001,"bert",'M' };
fprintf(fp, "%d %s %c", s.num, s.name, s.sex);
//关闭文件
fclose(fp);
fp = NULL;
return 0;
}
从文件输入不同类型数据
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
int num;
char name[10];
char sex;
};
int main()
{
//打开文件
FILE* fp = fopen("test.dat", "r");
if (fp == NULL)
{
perror("fopen");
exit(0);
}
//从文件输入不同类型数据
struct Stu s = { 0 };
fscanf(fp,"%d %s %c", &s.num, s.name, &s.sex);
fprintf(stdout, "%d %s %c", s.num, s.name, s.sex); //输出不同类型数据到stdout标准输出流(终端),和printf一样
//关闭文件
fclose(fp);
fp = NULL;
return 0;
}