思维导图

一、将当前的时间写入到time.txt的文件中,如果ctrl+c退出之后,在再次执行支持断点续写
1.2022-04-26 19:10:20
2.2022-04-26 19:10:21
3.2022-04-26 19:10:22
//按下ctrl+c停止,再次执行程序
4.2022-04-26 20:00:00
5.2022-04-26 20:00:01
代码
cpp
#include <25041head.h>
int line();
int main(int argc, const char *argv[])
{
int fd=open("./time.txt",O_RDWR | O_CREAT |O_APPEND,0777);
time_t t;
while(1)
{
time(&t);
//转换为 xxxx年xx月xx日 xx时xx分xx秒
struct tm *s=localtime(&t);
if(NULL==s)
{
ERRLOG("localtime error..");
}
char now_time[128]="";
lseek(fd,0,SEEK_END);
snprintf(now_time,sizeof(now_time),"%d.%04d-%02d-%02d %02d:%02d:%02d\n",\
line()+1,s->tm_year+1900,s->tm_mon+1,s->tm_mday,\
s->tm_hour,s->tm_min,s->tm_sec);
write(fd,now_time,strlen(now_time));
fprintf(stdout,"%s",now_time);
sleep(1);
}
return 0;
}
//计算当前行数
int line()
{
FILE *fp=fopen("time.txt","r");
if(NULL==fp)
{
ERRLOG("fopen error..");
}
int count=0;
while(1)
{
char ch=fgetc(fp);
if(EOF==ch)
{
break;
}
if('\n'==ch)
count++;
}
if(EOF==fclose(fp))
{
printf("fclose error..\n");
return -1;
}
return count;
}
运行结果


二、使用文件IO函数实现图片的拷贝
代码
cpp
#include <25041head.h>
int main(int argc, const char *argv[])
{
umask(0);
int fd=open("./my.bmp",O_RDONLY);
int fd_c=open("copy.bmp",O_RDWR | O_CREAT | O_TRUNC,0777);
char buf[128]="";
while(1)
{
memset(buf,0,sizeof(buf));
int res=read(fd,buf,sizeof(buf)-1);
if(res==0)
break;
if(-1==res)
{
ERRLOG("read error..");
}
write(fd_c,buf,sizeof(buf)-1);
}
if(-1==close(fd)&&-1==close(fd_c))
{
ERRLOG("close error..");
}
printf("图片拷贝成功!\n");
return 0;
}
运行结果

三、使用文件IO读取图片 文件大小、文件偏移量,宽度,高度。

1.bmp文件头(bmp file header):提供文件的格式、大小等信息 (14字节)

2.位图信息头(bitmap information):提供图像数据的尺寸、位平面数、压缩方式、颜色索引等信息(50字节)

3.位图数据(bitmap data):就是图像数据啦
代码
cpp
#include <25041head.h>
int main(int argc, const char *argv[])
{
//打开bmp图片文件
int fd=open("./my.bmp",O_RDONLY);
if(-1==fd)
{
ERRLOG("open error..");
}
lseek(fd,2,SEEK_SET);
//把光标定位到文件计算大小
int size;
if(-1== read(fd,&size,4))
{
ERRLOG("read error..");
}
printf("图片文件大小为%d字节\n",size);
//把光标定位到记录文件偏移量的位置
lseek(fd,10,SEEK_SET);
int offset;
if(-1==read(fd,&offset,4))
{
ERRLOG("read error..");
}
printf("图片文件偏移量为%d字节\n",offset);
//宽度
lseek(fd,18,SEEK_SET);
int width;
if(-1==read(fd,&width,4))
{
ERRLOG("read error..");
}
printf("图片宽度为%d像素\n",width);
//高度,连续读取,无需偏移
int height;
if(-1==read(fd,&height,4))
{
ERRLOG("read error..");
}
printf("图片高度为%d像素\n",height);
//关闭文件
if(-1==close(fd))
{
ERRLOG("close error..");
}
return 0;
}
运行结果
