📄 file操作6.cpp
字号:
/*
程序名称: 文件操作 -- 格式化数据读取
使用函数: fopen, fclose, ferror, fprintf, fscanf
程序功能: 非字符型数据关于文件的读取 -- struct数据
日期: 2008-02-28
作者: zuojianhua
*/
#include <stdio.h>
#include <string.h>
struct student
{
char name[20];
int age;
}stu[3], des[3];
main()
{
FILE *fp = NULL;
stu[0].age = 20;
strcpy(stu[0].name, "NULL");
stu[1].age = 30;
strcpy(stu[1].name, "Lijie");
stu[2].age = 43;
strcpy(stu[2].name, "wangxing");
for(int i=0; i<3; i++)
{
des[i].age = 0;
memset(des[i].name, '\0', 20);
}
// 1. 以文本文件的格式写入
fp = fopen("c:\\zuojianhua\\struct.txt", "w");
if( !fp )
{
printf("The file can not open.");
return 0;
}
// 2. 以格式化写入文件
for(i=0; i<3; i++)
{
fprintf(fp, "%s\t%d\n", stu[i].name, stu[i].age);
}
fclose(fp);
// 3. 重新打开文件
fp = fopen("c:\\zuojianhua\\struct.txt", "r");
if( !fp )
{
printf("The file can not open.");
return 0;
}
// 4. 以二进制文件的格式读取
for(i=0; i<3; i++)
{
fscanf(fp, "%s%d", des[i].name, &(des[i].age));
}
// 5. 打印读取结构
for(i=0; i<3; i++)
{
printf("%s, %d\n", des[i].name, des[i].age);
}
fclose(fp);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -