写一个日志文件,将程序启动后,每一秒的时间写入到文件中
实现代码
#include <myhead.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
char buf[128] = "";
FILE *fp = fopen("./time.txt", "w");
if (fp == NULL)
return 0;
for (int i = 0; i < 20; i++)
{
time_t sys_time = time(NULL);
struct tm *time_ptr = localtime(&sys_time);
snprintf(buf, sizeof (buf),"%d.\t%4d-%2d-%2d %2d:%2d:%2d\n",
i + 1,
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);
fwrite(buf, strlen(buf), 1, fp);
printf("%s", buf);
sleep(1);
}
fclose(fp);
return 0;
}
运行结果:
1. 2024- 7-29 21: 1:28
2. 2024- 7-29 21: 1:29
3. 2024- 7-29 21: 1:30
4. 2024- 7-29 21: 1:31
5. 2024- 7-29 21: 1:32
6. 2024- 7-29 21: 1:33
7. 2024- 7-29 21: 1:34
8. 2024- 7-29 21: 1:35
9. 2024- 7-29 21: 1:36
10. 2024- 7-29 21: 1:37
11. 2024- 7-29 21: 1:38
12. 2024- 7-29 21: 1:39
13. 2024- 7-29 21: 1:40
14. 2024- 7-29 21: 1:41
15. 2024- 7-29 21: 1:42
16. 2024- 7-29 21: 1:43
17. 2024- 7-29 21: 1:44
18. 2024- 7-29 21: 1:45
19. 2024- 7-29 21: 1:46
20. 2024- 7-29 21: 1:47
使用fread、fwrite完成两个文件的拷贝
#include <myhead.h>
int main(int argc, char const *argv[])
{
FILE *fp1 = fopen("fread.c", "r");
FILE *fp2 = fopen("paste.txt", "w");
if (fp1 == NULL || fp2 == NULL)
{
perror("fopen error");
return -1;
}
char cpy[128];
int bytes_read;
while ((bytes_read = fread(cpy, 1, sizeof(cpy) - 1, fp1)) > 0)
{
cpy[bytes_read] = '\0'; // 确保字符串以空字符结尾
fwrite(cpy, 1, bytes_read, fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
运行结果:
#include <myhead.h>
int main(int argc, char const *argv[])
{
FILE *fp1 = fopen("fread.c", "r");
FILE *fp2 = fopen("paste.txt", "w");
if (fp1 == NULL || fp2 == NULL)
{
perror("fopen error");
return -1;
}
char cpy[128];
int bytes_read;
while ((bytes_read = fread(cpy, 1, sizeof(cpy) - 1, fp1)) > 0)
{
cpy[bytes_read] = '\0'; // 确保字符串以空字符结尾
fwrite(cpy, 1, bytes_read, fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
实现对bmp图像的读写操作,打马赛克(bushi
实现代码:
#include <myhead.h>
int main(int argc, const char *argv[])
{
//定义文件指针
FILE *fp = NULL;
if ((fp = fopen("./haha.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, 0};
long start =(54+3 * 720 * 315);
//fseek(fp,start, SEEK_SET);
for (int i = 0;i < 50; i++)
{
fseek(fp, ( start+3*720*i +3*230), SEEK_SET);//移动到头部
for (int j = 0; j < 150; j++)
fwrite(color, sizeof(color), 1, fp);//打印色块
//720*570
}
//关闭文件
fclose(fp);
return 0;
}
运行结果: