一、思维导图
二、练习题1
使用 fread 和 fwrite 将一张任意bmp图片改成德国旗
#include <stdio.h>
int main()
{
FILE* fp=fopen("rising_freedom.bmp", "r+");
if(NULL==fp)
{
perror("fopen");
return 1;
}
int bmp_size=0;
int bmp_width=0;
int bmp_height=0;
fseek(fp,2,SEEK_SET);
fread(&bmp_size,4,1,fp);
printf("图片大小为:%d\n", bmp_size);
fseek(fp,18,SEEK_SET);
fread(&bmp_width,4,1,fp);
fread(&bmp_height,4,1,fp);
printf("图片像素为:%d * %d\n", bmp_width, bmp_height);
fseek(fp,54,SEEK_SET);
unsigned char bgr_b[3]={0,0,0}; //黑
unsigned char bgr_r[3]={0,0,255}; //红
unsigned char bgr_y[3]={0,255,255}; //金黄色
for(int i=0; i<bmp_width*(bmp_height/3); i++)
{
fwrite(bgr_y,3,1,fp);
}
for(int i=0; i<bmp_width*(bmp_height/3); i++)
{
fwrite(bgr_r,3,1,fp);
}
for(int i=0; i<bmp_width*(bmp_height/3); i++)
{
fwrite(bgr_b,3,1,fp);
}
printf("旗子绘制完成!\n");
fclose(fp);
return 0;
}
三、练习题修改
#include <stdio.h>
#include <stdlib.h>
struct Data
{
char name[20];
double math;
double chinese;
double englishl;
double physical;
double chemical;
double biological;
};
typedef struct Student
{
union
{
struct Data data;
struct Student* tail;
};
struct Student* next;
struct Student* prev;
}stu_t;
stu_t* create_stu()
{
stu_t* node=calloc(1,sizeof(stu_t));
node->next=NULL;
node->prev=NULL;
node->tail=node;
return node;
}
void insert_stu(stu_t* head, struct Data data)
{
stu_t* newstu=create_stu();
newstu->data=data;
head->tail->next=newstu;
newstu->next=NULL;
newstu->prev=head->tail;
head->tail=newstu;
}
void show(stu_t* head)
{
stu_t* p=head->next;
while(p!=NULL)
{
printf("姓名:%s\n", p->data.name);
printf("数学:%lf\n", p->data.math);
printf("语文:%lf\n", p->data.chinese);
printf("英语:%lf\n", p->data.english);
printf("物理:%lf\n", p->data.physical);
printf("化学:%lf\n", p->data.chemical);
printf("生物:%lf\n", p->data.biological);
printf("-----------------------------\n");
p=p->next;
}
}
void save(stu_t* head, const char* filename)
{
FILE* fp=fopen(filename,"w");
stu_t* p=head->next;
while(p!=NULL)
{
fprintf(fp,"%s %lf %lf %lf %lf %lf %lf\n", p->data.name, p->data.math, p->data.chinese, p->data.english, p->data.physical, p->data.chemical, p->data.biological);
p=p->next;
}
fclose(fp);
}
void load(stu_t* head, const char* filename)
{
FILE* fp=fopen(filename,"r");
if(fp==NULL)
{
printf("文件不存在!\n");
return;
}
while(1)
{
struct Data data={0};
int res=fscanf(fp,"%s %lf %lf %lf %lf %lf %lf\n", data.name, &data.math, &data.chinese, &data.english, &data.physical, &data.chemical, &data.biological);
if(res==EOF)
{
break;
}
insert_stu(head,data);
}
fclose(fp);
}
int main()
{
stu_t* head=create_stu();
struct Data d1={"张三",99,99,99,99,99,99};
struct Data d2={"李四",88,88,88,88,88,88};
struct Data d3={"王五",77,77,77,77,77,77};
insert_stu(head, d1);
insert_stu(head, d2);
insert_stu(head, d3);
save(head,"stu.txt");
stu_t* head2=create_stu();
load(head2,"stu.txt");
show(head2);
return 0;
}