1个回答
展开全部
从键盘输入4个学生的有关数据,然后把它们转存到磁盘文件上去,接着把它们输出到终端。
#include <stdio.h>
#define SIZE 4
struct student_type
{
char name[20];
int num;
int age;
char addr[15];
}stud[SIZE];
void save()
{
FILE * fp;
int i;
if ((fp = fopen("D:\\stu_list.txt", "wb")) == NULL)
{
printf("cannot open file\n");
return;
}
for (i = 0; i < SIZE; i++)
{
if(fwrite(&stud[i], sizeof(struct student_type), 1, fp) != 1)
printf("file write error.\n");
}
fclose(fp);
}
void main()
{
printf("sizeof(struct stud) = %d\n", sizeof(student_type));
printf("Please input the 4 student information,including name,num,age,address\n");
int i;
for(i = 0; i < SIZE; i++)
scanf("%s%d%d%s", stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
save();
printf("\nThe information of the 4 students is:\n");
FILE* fp;
fp = fopen("D:\\stu_list.txt", "rb");
for (i = 0; i < SIZE; i++)
{
fread(&stud[i], sizeof(struct student_type), 1, fp);
printf("%-10s %4d %4d %-15s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
}
fclose(fp);
}
#include <stdio.h>
#define SIZE 4
struct student_type
{
char name[20];
int num;
int age;
char addr[15];
}stud[SIZE];
void save()
{
FILE * fp;
int i;
if ((fp = fopen("D:\\stu_list.txt", "wb")) == NULL)
{
printf("cannot open file\n");
return;
}
for (i = 0; i < SIZE; i++)
{
if(fwrite(&stud[i], sizeof(struct student_type), 1, fp) != 1)
printf("file write error.\n");
}
fclose(fp);
}
void main()
{
printf("sizeof(struct stud) = %d\n", sizeof(student_type));
printf("Please input the 4 student information,including name,num,age,address\n");
int i;
for(i = 0; i < SIZE; i++)
scanf("%s%d%d%s", stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
save();
printf("\nThe information of the 4 students is:\n");
FILE* fp;
fp = fopen("D:\\stu_list.txt", "rb");
for (i = 0; i < SIZE; i++)
{
fread(&stud[i], sizeof(struct student_type), 1, fp);
printf("%-10s %4d %4d %-15s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
}
fclose(fp);
}
追问
您好!我对fopen函数也不太清楚,可以给一些操作给予必要的文字解释吗
追答
打开文件流,就可以操作
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询