顺序读写函数练习使用
代码如下:
1.fputc和fgetc的练习使用
int main()
{
FILE* pr = fopen("date1.txt", "w");//在文件date1中写入数据
if (pr == NULL)
{
return 1;
}
fputc('b', pr);//fputc
fclose(pr);
pr = NULL;
FILE* ppr = fopen("date1.txt", "r");//在文件date1中调用数据
if (ppr == NULL)
{
return 1;
}
char n = fgetc(ppr);
printf("读取出来的字符为%c", n);
fclose(ppr);
ppr = NULL;
return 0;
}
2.fputs和fgets的练习使用
int main()
{
FILE* pr = fopen("date2.txt", "w");//在文件date2中写入数据
if (pr == NULL)
{
return 1;
}
fputs("hello world", pr);
fclose(pr);
pr = NULL;
FILE* ppr = fopen("date2.txt", "r");//在文件date2中调用数据
if (ppr == NULL)
{
return 1;
}
char arr[20] = { 0 };
fgets(arr, 10, ppr);
printf("%s", arr);
fclose(ppr);
ppr = NULL;
return 0;
}
3.fprintf和fscanf的练习使用
struct Stu
{
char name[20];
int age;
float score;
};
int main()
{
struct Stu s = { "lisi", 20, 90.3f };
struct Stu x = { 0 };
FILE*pf = fopen("data.txt", "w");//在文件date3中写入数据
if (pf == NULL)
{
return 1;
}
fprintf(pf, "%s %d %.1f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
FILE* pff = fopen("data.txt", "r");//在文件date3中调用数据
if (pff == NULL)
{
return 1;
}
fscanf(pff, "%s %d %f", x.name, &(x.age), &(x.score));
fprintf(stdout, "%s %d %.1f\n", x.name, x.age, x.score);
fclose(pff);
pff = NULL;
return 0;
}
4.fread和fwrite的练习使用
struct people
{
char name[20];
int age;
float score;
};
int main()
{
struct people x = { "lisi",20,65.3f };
struct people z = { 0 };
FILE* pr = fopen("date4.txt", "wb");
if (pr == NULL)
{
return 1;
}
fwrite(&x, sizeof(x), 1, pr);
fclose(pr);
pr = NULL;
FILE* prr = fopen("date4.txt", "rb");
if (prr == NULL)
{
return 1;
}
fread(&z, sizeof(z), 1, prr);
fprintf(stdout, "%s %d %.1f\n", z.name, z.age, z.score);
fclose(prr);
prr = NULL;
return 0;
}