将当前时间写入time.txt
文件,支持断点续写。 #include "headhs.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h> // 时间相关函数
#include <unistd.h> // 操作系统交互函数:sleep
#include <signal.h> // 信号处理相关函数:SIGINT// 信号处理函数
void signal_c(int signal)
{printf("\n程序已终止\n");exit(0); // 正常退出程序
}int main(int argc, const char *argv[])
{// 注册信号处理函数,捕获 Ctrl+C 信号signal(SIGINT, signal_c);// 打开文件(追加模式)FILE *fp = fopen("time.txt", "a+");if (fp == NULL){pt_er("无法打开文件");}// 获取当前行号int line_number = 0;char line[256];while (fgets(line, sizeof(line), fp)){line_number++;}// 无限循环,每秒写入当前时间while (1){time_t sec;time(&sec); // 获取当前时间struct tm *t = localtime(&sec); // 转换为本地时间if (t == NULL){pt_er("localtime error"); // 打印错误信息}// 格式化时间并写入文件fprintf(fp,"%d.%04d-%02d-%02d %02d:%02d:%02d\n",line_number + 1, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,t->tm_hour, t->tm_min, t->tm_sec);fflush(fp); // 刷新缓冲区,确保数据写入文件// 在终端打印当前时间 printf("%d.%04d-%02d-%02d %02d:%02d:%02d\n",line_number + 1, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,t->tm_hour, t->tm_min, t->tm_sec);line_number++; // 行号加 1sleep(1); // 休眠 1 秒}fclose(fp);return 0;
}

使用fwrite
和fread
函数实现图片拷贝。 #include <stdio.h>
#include <stdlib.h>
#include "headhs.h"
int main(int argc, const char *argv[])
{// 检查命令行参数if (argc != 3){printf("用法: %s <源文件> <目标文件>\n",argv[0]);return 1;}// 打开源文件(二进制读取模式)FILE *src_file = fopen(argv[1], "rb");if (src_file == NULL){perror("无法打开源文件");return 1;}// 打开目标文件(二进制写入模式)FILE *dest_file = fopen(argv[2], "wb");if (dest_file == NULL){perror("无法打开目标文件");fclose(src_file);return 1;}// 定义缓冲区char buffer[1024];size_t bytes_read;// 逐块读取源文件并写入目标文件while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file))){fwrite(buffer, 1, bytes_read, dest_file);}// 检查是否读取完成if (feof(src_file)){printf("图片拷贝成功!\n");}else{perror("拷贝过程中发生错误");}// 关闭文件fclose(src_file);fclose(dest_file);return 0;
}

