1> 写一个日志文件,将程序启动后,每一秒的时间写入到文件中
#include <myhead.h>
int main(int argc,const char *argv[])
{FILE *fp = NULL;if((fp=fopen("./log.txt","r"))==NULL) {perror("open error1");return -1;}char buf[10] = "";int count = 0;while(1){char *ptr = fgets(buf, sizeof(buf), fp);if(ptr == NULL) {break;}if(buf[strlen(buf)-1] == '\n'){count++;}}fclose(fp);FILE *fp1 = NULL;if((fp1=fopen("./log.txt","a"))==NULL) {perror("open error2");return -1;}time_t sys_time = time(NULL);struct tm *p = localtime(&sys_time);int old_time = p->tm_sec;while(1){time_t sys_time1 = time(NULL);struct tm *p1 = localtime(&sys_time1);if((p1->tm_sec-old_time+60)%60==1){old_time = p1->tm_sec;fprintf(fp1,"%d:%4d-%2d-%2d %2d.%2d.%2d\n",count+1,p1->tm_year+1900,p1->tm_mon+1,p1->tm_mday,p1->tm_hour,p1->tm_min,p1->tm_sec);count++;fgetc(fp1);}}fclose(fp1);return 0;
}
2> 使用fread、fwrite完成两个文件的拷贝
不允许只读写一次
#include <myhead.h>
int main(int argc,const char *argv[])
{if(argc!=3){perror("error");return -1;}FILE *fp1 = NULL;if((fp1=fopen(argv[1],"r"))==NULL){perror("fopen error");return -1;}FILE *fp2 = NULL;if((fp2=fopen(argv[2],"a"))==NULL){perror("fopen error");return -1;} char buf[10]="";while(1){int res=fread(buf,sizeof(buf),1,fp1);if(res<1){break;}fwrite(buf,sizeof(buf),1,fp2);}fclose(fp1);fclose(fp2);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;//将文件光标偏移2个字节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;
}