一、作业
1.写一个日志文件,将程序启动后的每一秒时间写入到文件中
代码:
#include<myhead.h>
#include<time.h>
//判断原本文件中的行数
int len_txt(FILE *fp)
{
char buf=0;
int count =1;
while(1)
{
buf=fgetc(fp);
if(buf==EOF)
{
break;
}
if(buf=='\n')
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
//设定时间变量
time_t new_time;
time_t old_time ;
struct tm *systime;
//打开一个存储日志信息的文件
FILE *fp = NULL;
if((fp=fopen("./time.txt","a+"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[128] = "";//存放转变后的字符串的字符数组
int len=0;
len = len_txt(fp);
while(1)
{
new_time = time(NULL);
systime = localtime(&new_time);
if(new_time!=old_time)
{
old_time = new_time;
sprintf(buf,"%d、%4d-%2d-%2d %2d:%2d:%2d\n",\
++len,\
systime->tm_year+1900,\
systime->tm_mon+1,\
systime->tm_mday,\
systime->tm_hour,\
systime->tm_min,\
systime->tm_sec);
fwrite(buf,sizeof(buf),1,fp);
fflush(fp);
}
}
fclose(fp);
return 0;
}
运行:
2.使用fread和fwrite完成图像的读写操作
代码:
#include<myhead.h>
#define MAX 32
int main(int argc, const char *argv[])
{
if(argc != 3)
{
printf("输入文件错误\n");
return -1;
}
FILE *fp1 = fopen(argv[1],"r");
if(NULL == fp1)
{
perror("fopen argv[1] error");
return -1;
}
FILE *fp2 = fopen(argv[2],"w");
if(NULL == fp2)
{
perror("fopen argv[2] error");
return -1;
}
char buf[MAX] = "";
int res=0;
while((res = fread(buf,1,MAX,fp1))!=0)
{
fwrite(&buf,1,res,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;
fseek(fp,2,SEEK_SET);
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,0,255};//正红
for(int i=0;i<960/2;i++)
{
for(int j=0;j<1280;j++)
{
fwrite(color,sizeof(color),1,fp);
}
}
return 0;
}