作业:
1> 写一个日志文件,将程序启动后,每一秒的时间写入到文件中
1、2024- 7-29 10:31:19
2、2024- 7-29 10:31:20
3、2024- 7-29 10:31:21
ctrl+c:停止程序
./a.out
4、2024- 7-29 10:35:06
5、2024- 7-29 10:35:07
6、2024- 7-29 10:35:08
#include <myhead.h>int main(int argc, const char *argv[])
{FILE *fp = NULL;if((fp = fopen("./time.txt","w")) == NULL){perror("fopen error");return -1;}char buf[128] = "";char buff[128] = "";int count = 1;while(1){ time_t sys_time = time(NULL);struct tm *time_ptr = localtime(&sys_time);sprintf(buf,"%d、%4d-%2d-%2d %2d:%2d:%d\n",\count,\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);fflush(fp);if(strcmp(buf,buff) != 0 ){fwrite(&count,sizeof(count),1,fp);fwrite(buf,strlen(buf),1,fp); strcpy(buff,buf);count++;}}fclose(fp);return 0;
}
2> 使用fread、fwrite完成两个文件的拷贝
不允许只读写一次
#include <myhead.h>int main(int argc, const char *argv[])
{FILE *sfp=NULL;FILE *dfp=NULL;if((sfp=fopen("./usr3.txt","r"))==NULL){perror("fopen error");return -1;}if((dfp=fopen("./usr2.txt","w"))==NULL){perror("fopen error");return -1;}char buf[20] = "";int res = 0;while((res = fread(buf,sizeof(buf),1,sfp))!=0){fwrite(buf,sizeof(buf),res,dfp); }fclose(sfp);fclose(dfp);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] = {0,0,255};for(int i =0;i<960/2;i++){for(int j=0;j<1280;j++){fwrite(color,sizeof(color),1,fp);}}fclose(fp);return 0;
}
4> 君子作业:给图像打马赛克