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>
FILE *log_file;
time_t last_time;
void write_time_to_file()
{
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
if (rawtime == last_time)
{
return; // 如果时间没有变化,不写入文件
}
last_time = rawtime;
timeinfo = localtime(&rawtime);
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S\n", timeinfo);
fprintf(log_file, "%s", buffer);
fflush(log_file);
}
int main()
{
log_file = fopen("log.txt", "a");
if (log_file == NULL)
{
printf("无法打开日志文件\n");
return 1;
}
while (1)
{
write_time_to_file();
}
return 0;
}
2> 使用fread、fwrite完成两个文件的拷贝
不允许只读写一次
#include <stdio.h>
int main()
{
FILE *srcFile = NULL;
FILE *dstFile = NULL;
char buffer[1024]; // 缓冲区大小可以根据需要调整
size_t bytesRead;
// 打开源文件和目标文件
srcFile = fopen("source.txt", "rb");
dstFile = fopen("destination.txt", "wb");
if (srcFile == NULL || dstFile == NULL)
{
printf("无法打开文件!\n");
return 1;
}
// 循环读取并写入数据,直到到达文件末尾
while ((bytesRead = fread(buffer, 1, sizeof(buffer), srcFile)) > 0)
{
fwrite(buffer, 1, bytesRead, dstFile);
}
// 关闭文件
fclose(srcFile);
fclose(dstFile);
printf("文件拷贝完成!\n");
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;
}