代码练习
使用fread和fwrite完成两个文件的拷贝
#include<myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp = NULL;
//重新以只读的形式打开文件
if((fp = fopen("./OIP-C.bmp", "r")) == NULL)
{
perror("fopen error");
return -1;
}
FILE *fp1=NULL;
if((fp1=fopen("./text.bmp","w"))==NULL)
{
perror("fopen error");
return -1;
}
char head[54]="";
unsigned char color[3];
fread(head, sizeof(head), 1, fp); //读取头
fwrite(head, sizeof(head), 1, fp1);//写入头
while(fread(color,sizeof(char),3,fp)==3)//读取像素点
{
fwrite(color,sizeof(char),3,fp1);//写入像素点
}
//关闭文件
fclose(fp);
fclose(fp1);
return 0;
}
效果图
使用read、write完成两个文件的拷贝
#include<myhead.h>
int main(int argc, const char *argv[])
{
//定义文件描述符变量
int fd = -1;
if((fd = open("./text.bmp", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
int fd1=-1;
if((fd1=open("./work3.bmp",O_WRONLY))==-1)
{
perror("open error");
return -1;
}
char head[54]="";
unsigned char color[3]="";
lseek(fd, 0, SEEK_SET); //将光标移到开头
read(fd,head, 54);//读取头
write(fd1,head,54);//写入头
//将光标偏移到矩阵部分
lseek(fd, 54, SEEK_SET);
while(read(fd,color,sizeof(color))==3)//读取像素
{
write(fd1,color,sizeof(color));//写入像素
}
//关闭文件
close(fd);
close(fd1);
return 0;
}
效果图
将时间在文件中跑起来
#include <myhead.h>
//将时间在文件中跑起来
int main(int argc, const char *argv[])
{
//打开时间文件
FILE *fp=NULL;
if((fp=fopen("./time.txt","a+"))==NULL)
{
perror("fopen error");
return -1;
}
//循环计算已有行号
int line=1;
while(1)
{
char c=fgetc(fp);
if(c=='\n')
line++;
if(c==EOF)
break;
}
//判断新旧时间
char time_buf[128]="";
struct tm *t;
time_t Old_Time,sysTime;
while(1)
{
sysTime=time(NULL);
if(Old_Time!=sysTime)
{
Old_Time=sysTime;
t=localtime(&sysTime);
snprintf(time_buf,sizeof(time_buf),"%d:%2d:%2d:%2d\n",\
line,t->tm_hour,t->tm_min,t->tm_sec);
printf("%s",time_buf);
fputs(time_buf,fp);
line++;
fflush(fp);
}
}
fclose(fp);
return 0;
}
效果图
思维导图