一、相关函数练习
1.写一个日志文件,将程序启动后,每一秒的时间写入到文件中
1> log.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
//定义文件指针
FILE *fp = NULL;
//以追加形式打开 log.txt 文件
if((fp = fopen("log.txt", "a+")) == NULL)
{
perror("fopen error\n");
return -1;
}
//定义变量记录行数
int line = 0;
char buf[128] = "";
//读取文件,记录行数
while(1)
{
//清空容器
bzero(buf, sizeof(buf));
if( fgets(buf, sizeof(buf), fp) == NULL)
{
break; //说明文件读取结束
}
//行数变化
line++;
}
//写入时间日志逻辑
while(1)
{
//定义变量存储秒数
time_t sys_time1,sys_time2;
time(&sys_time1);
//判断时间变化
while(1)
{
time(&sys_time2);
if(sys_time2 - sys_time1 >= 1)
{
break;
}
}
//将秒数转换为结构体
struct tm *time_ptr = localtime(&sys_time2);
line++;
fprintf(fp, "%6d. %4d-%2d-%2d %2d:%2d:%2d\n",
line,
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);
}
return 0;
}
2.程序运行截图
![](https://i-blog.csdnimg.cn/direct/4b3dc85dfce144fa86062a74b209f067.png)
2.使用fread、fwrite完成两个文件的拷贝
1> 09test.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
//判断传入的文件个数
if(argc != 3)
{
//
fputs("input file error\n", stderr);
return -1;
}
//定义源文件指针
FILE *sfp = NULL;
if((sfp = fopen(argv[1], "r")) == NULL)
{
printf("%s fopen error\n", argv[1]);
return -1;
}
//定义目标文件指针,以只读的形式打开文件
FILE *dfp = NULL;
if((dfp = fopen(argv[2], "w")) == NULL)
{
printf("%s fopen error\n", argv[2]);
return -1;
}
//定义搬运工
char buf[12] = "";
while(1)
{
if((fread(buf, sizeof(buf), 1, sfp) < 1))
{
break;
}
fwrite(buf, sizeof(buf), 1, dfp);
}
//关闭文件
fclose(sfp);
fclose(dfp);
return 0;
}
2> 程序运行截图
![](https://i-blog.csdnimg.cn/direct/6092cfc3915547bf96dc8f24d9c2db88.png)
3.实现对bmp图像的读写操作
1> bmp.c
#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 x=0; x<960; x++) //外行
{
for(int y=0;y<1280; y++) //内列
{
if((x%12==0) && (y%16==0))
{
for(int i=x; i<x+12&&i<960; i++)
{
fread(color, sizeof(color), 1, fp);
for(int j=y; j<y+16&&j<1280; j++)
{
fwrite(color, sizeof(color), 1, fp);
}
}
}
}
}
//关闭文件
fclose(fp);
return 0;
}
2> 程序运行截图
![](https://i-blog.csdnimg.cn/direct/830bc30935bd4f218104b51857899542.bmp)
![](https://i-blog.csdnimg.cn/direct/467863346c964900827c33ccc8041378.bmp)