一、思维导图
二、练习题
1、写一个日志文件,将程序启动后,每一秒的时间写入到文件中
#include<myhead.h>
int main(int argc, const char *argv[])
{
//定义日志计数器文件指针
FILE *log = NULL;
if((log = fopen("./daily_log","r")) == NULL)
{
perror("fopen error");
return -1;
}
//定义容器接收日志文件计数次数
long count = 1;
fread(&count,sizeof(count),1,log);
//关闭文件
fclose(log);
//定义两个容器存储时间信息和更新时间信息
char new_time[128] = "";
char old_time[128] = "";
while(1)
{
//定义变量存储秒数
time_t sys_time = time(NULL);
//将秒数转换为结构体
struct tm *time_ptr = localtime(&sys_time);
snprintf(new_time,sizeof(new_time),"%4d-%2d-%2d %2d:%2d:%2d\n",\
time_ptr->tm_year+1900,\
time_ptr->tm_mon+1,\
time_ptr->tm_mday,\
time_ptr->tm_hour,\
time_ptr->tm_min,\
time_ptr->tm_sec);
//新时间与旧时间不相等
if(strcmp(new_time,old_time) != 0)
{
//输出时间
printf("%ld:%s\n",count,new_time);
count++;
//将count重新写入日志文件计数器
//定义日志计数器文件指针
FILE *log = NULL;
if((log = fopen("./daily_log","w")) == NULL)
{
perror("fopen error");
return -1;
}
fwrite(&count,sizeof(count),1,log);
//关闭文件
fclose(log);
//更新时间信息容器
strcpy(old_time,new_time);
}
}
return 0;
}
2、使用fread、fwrite完成两个文件的拷贝(不允许只读写一次)
#include<myhead.h>
int main(int argc, const char *argv[])
{
//判断终端输入
if(argc != 3)
{
printf("输入格式错误,请重新输入\n");
printf("useage:./a.out srcname,destname\n");
}
//定义文件指针
FILE *src = NULL;
FILE *dest = NULL;
if((src = fopen(argv[1],"r")) == NULL)
{
perror("src file fopen error");
return -1;
}
if((dest = fopen(argv[2],"w")) == NULL)
{
perror("dest file fopen error");
return -1;
}
//定义容器存储读取的数据
char buf[128] = "";
//将数据存入容器并读取到目标文件中
int res = 0;
do
{
res = fread(buf,1,sizeof(buf),src);
fwrite(buf,1,res,dest);
}while(res == 128);
printf("拷贝成功\n");
//关闭文件
fclose(src);
fclose(dest);
return 0;
}
3、 实现对bmp图像的读写操作
#include<myhead.h>
int main(int argc, const char *argv[])
{
//定义文件指针
FILE *fp = NULL;
if((fp = fopen("./gg.bmp","r+")) == NULL)
{
perror("fopen error");
return -1;
}
//获取文件大小
int img_size = 0;
//将文件光标偏移两个字节
fseek(fp,2,SEEK_SET);
//读取4字节内容
fread(&img_size,sizeof(img_size),1,fp);
printf("size = %d\n",img_size);
//从头向前偏移54字节
fseek(fp,54,SEEK_SET);
//更改像素
unsigned char color[3] = {255,255,0};
for(int i=0;i<960/2;i++)
{
for(int j=0;j<1280;j++)
{
fwrite(color,sizeof(color),1,fp);
}
}
return 0;
}
4、 给图像打马赛克