1.思维导图
2.使用 fread 和 fwrite 函数,重写昨天的第2个作业
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student
{
char name[10];
int chinese;
int math;
int English;
int physics;
int chemistry;
int biology;
}stu,*stuptr;
typedef struct node
{
union
{
stu data;
int len;
};
struct node* next;
}node,*nodeptr;
nodeptr creat_head()
{
nodeptr h = (nodeptr)malloc(sizeof(node));
if(NULL == h)
{
printf("创建失败\n");
return NULL;
}
h->len = 0;
h->next = NULL;
return h;
}
nodeptr node_creat(stu arr)
{
nodeptr p = (nodeptr)malloc(sizeof(node));
if(NULL==p)
{
printf("创建失败\n");
return NULL;
}
p->data=arr;
p->next=NULL;
return p;
}
int node_add(stu arr,nodeptr h)
{
if(NULL==h)
{
printf("插入失败\n");
return 0;
}
nodeptr p=node_creat(arr);
p->next=h->next;
h->next=p;
h->len++;
return 1;
}
int show(nodeptr h)
{
if(NULL==h)
{
printf("遍历失败\n");
return 0;
}
nodeptr p=h;
while(p->next!=NULL)
{
p=p->next;
printf("姓名:%s\n",p->data.name);
printf("语文:%d\n",p->data.chinese);
printf("数学:%d\n",p->data.math);
printf("英语:%d\n",p->data.English);
printf("物理:%d\n",p->data.physics);
printf("化学:%d\n",p->data.chemistry);
printf("生物:%d\n",p->data.biology);
printf("------------------------\n");
}
}
int save(nodeptr h)
{
if(NULL==h)
{
printf("失败\n");
return 0;
}
FILE* fp = fopen("student.text","w");
nodeptr p=h;
for(int i=0;i<3;i++)
{
p=p->next;
fwrite(&p->data,sizeof(stu),1,fp);
}
fclose(fp);
return 1;
}
int load(nodeptr p)
{
FILE* fp = fopen("student.text","r");
while(1)
{
stu brr={0};
int res=fread(&brr,sizeof(stu),1,fp);
if(res==0){break;}
node_add(brr,p);
}
fclose(fp);
return 1;
}
int main(int argc, const char *argv[])
{
nodeptr h=creat_head();
stu arr1={"chen",99,88,99,88,98,88};
stu arr2={"yu",99,98,99,78,98,88};
stu arr3={"lin",99,88,99,98,98,98};
node_add(arr1,h);
node_add(arr2,h);
node_add(arr3,h);
save(h);
nodeptr b=creat_head();
load(b);
show(b);
show(h);
return 0;
}
结果
3.使用 fread 和 fwrite 将一张任意bmp图片改成德国国旗
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE* fp = fopen("gaoda.bmp","r+");
if(NULL==fp)
{
perror("fopen");
return 0;
}
int bmp_size=0,bmp_width=0,bmp_height=0;
fseek(fp,18,SEEK_SET);
fread(&bmp_width,4,1,fp);
fread(&bmp_height,4,1,fp);
int size=bmp_height*bmp_width;
fseek(fp,54,SEEK_SET);
unsigned char yellow[3] ={0,255,255};
unsigned char red[3]={0,0,255};
unsigned char black[3]={0,0,0};
for(int i=0;i<size;i++)
{
if(i>=0&&i<size/3)
{
fwrite(yellow,3,1,fp);
}
else if(i>=size/3&&i<2*size/3)
{
fwrite(red,3,1,fp);
}
else if(i>=2*size/3&&i<size)
{
fwrite(black,3,1,fp);
}
}
fclose(fp);
return 0;
}
标签:node,fp,return,int,标准,nodeptr,IO,printf
From: https://blog.csdn.net/Ma_Lin_/article/details/145016519