IO标准函数和时间函数
- 创业
- 2025-09-11 14:09:02

1、将当前的时间写入到time. txt的文件中,如果ctrl+c退出之后,在再次执行支持断点续写
1.2022-04-26 19:10:20
2.2022-04-26 19:10:21
3.2022-04-26 19:10:22
//按下ctrl+c停止,再次执行程序
4.2022-04-26 20:00:00
5.2022-04-26 20:00:01
#include <stdio.h> #include <time.h> #include <unistd.h> #include <signal.h> FILE *file; // 用于写入时间到文件 // 捕获 SIGINT 信号(Ctrl+C)处理函数 void handle_sigint(int sig) { if (file != NULL) { fclose(file); // 关闭文件 } printf("\nExiting gracefully...\n"); exit(0); // 退出程序 } int main(int argc, const char *argv[]) { signal(SIGINT, handle_sigint); // 捕获 SIGINT 信号,优雅退出 // 打开 time.txt 文件进行追加写入 file = fopen("time.txt", "a"); if (file == NULL) { perror("Failed to open time.txt"); return 1; } while (1) { time_t sec; time_t res = time(&sec); // 获取当前时间戳 struct tm *t = localtime(&sec); // 转换为本地时间 if (t == NULL) { perror("localtime error"); fclose(file); // 错误时关闭文件 return 1; } // 格式化并输出当前时间到文件 fprintf(file, "%d-%02d-%02d %02d:%02d:%02d\n", t->tm_year + 1900, // tm_year 是从 1900 年开始 t->tm_mon + 1, // tm_mon 是从 0 开始 t->tm_mday, // tm_mday 是日期 t->tm_hour, // tm_hour 是小时 t->tm_min, // tm_min 是分钟 t->tm_sec); // tm_sec 是秒 // 立即刷新文件缓冲区,以确保每次写入都能被保存 fflush(file); sleep(1); // 每秒写入一次 } // 关闭文件,虽然这个部分在无限循环中不会执行 fclose(file); return 0; }2、使用fwrite和fread函数实现图片的拷贝
prt sc ---截图
eog 文件名 ----》打开文件
#include <stdio.h> #include <stdlib.h> int main() { FILE *sourceFile, *destFile; char *sourceFilename = "source_image.jpg"; // 源文件名 char *destFilename = "destination_image.jpg"; // 目标文件名 // 打开源文件,读取模式 sourceFile = fopen(sourceFilename, "rb"); if (sourceFile == NULL) { perror("Error opening source file"); return 1; } // 打开目标文件,写入模式 destFile = fopen(destFilename, "wb"); if (destFile == NULL) { perror("Error opening destination file"); fclose(sourceFile); return 1; } // 获取源文件的大小 fseek(sourceFile, 0, SEEK_END); // 定位到文件末尾 long fileSize = ftell(sourceFile); // 获取文件大小 fseek(sourceFile, 0, SEEK_SET); // 将文件指针移回文件开头 // 为文件内容分配内存 unsigned char *buffer = (unsigned char *)malloc(fileSize); if (buffer == NULL) { perror("Memory allocation error"); fclose(sourceFile); fclose(destFile); return 1; } // 读取源文件内容 size_t bytesRead = fread(buffer, 1, fileSize, sourceFile); if (bytesRead != fileSize) { perror("Error reading source file"); free(buffer); fclose(sourceFile); fclose(destFile); return 1; } // 将内容写入目标文件 size_t bytesWritten = fwrite(buffer, 1, bytesRead, destFile); if (bytesWritten != bytesRead) { perror("Error writing to destination file"); free(buffer); fclose(sourceFile); fclose(destFile); return 1; } // 清理资源 free(buffer); fclose(sourceFile); fclose(destFile); printf("Image copied successfully.\n"); return 0; }IO标准函数和时间函数由讯客互联创业栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“IO标准函数和时间函数”
上一篇
day51shell