Linux 软件实现建立一个文件夹,在此文件夹中建立一个log记录文件(也是软件实现)。 键盘随机输入一个数,通过子线程把这个数记录到log文件里面去。 同时记录输入数据的时间,并且每次输入的数据不能覆盖前面输入的数据。 编译进程需要添加参数-lpthread
时间: 2023-12-03 14:44:01 浏览: 98
以下是一个简单的实现,使用了pthread库和ctime库:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
void *log_input(void *arg);
int main()
{
char folder_name[100] = "my_folder"; // 文件夹名
char log_file_name[100] = "input_log.txt"; // log文件名
char path[200]; // 文件夹路径+文件名
// 创建文件夹
char mkdir_cmd[200];
sprintf(mkdir_cmd, "mkdir %s", folder_name);
system(mkdir_cmd);
// 创建log文件
sprintf(path, "%s/%s", folder_name, log_file_name);
FILE *log_file = fopen(path, "w");
if (log_file == NULL) {
printf("Failed to create log file.\n");
exit(1);
}
fprintf(log_file, "Input log:\n");
fclose(log_file);
// 创建子线程
pthread_t tid;
if (pthread_create(&tid, NULL, log_input, (void *)path) != 0) {
printf("Failed to create thread.\n");
exit(1);
}
// 主线程输入数值
srand(time(NULL));
while (1) {
int input_num = rand() % 100; // 随机数
time_t current_time = time(NULL); // 当前时间
char time_str[30];
strftime(time_str, 30, "%Y-%m-%d %H:%M:%S", localtime(¤t_time)); // 格式化时间字符串
// 写入log文件
log_file = fopen(path, "a");
fprintf(log_file, "%s: %d\n", time_str, input_num);
fclose(log_file);
sleep(1);
}
return 0;
}
void *log_input(void *arg)
{
char *path = (char *)arg;
char tail_cmd[200];
sprintf(tail_cmd, "tail -f %s", path); // 使用tail -f命令实现动态显示log文件内容
system(tail_cmd);
return NULL;
}
```
编译命令为:
```
gcc -o log_input log_input.c -lpthread
```
运行时,将生成一个名为`my_folder`的文件夹,并在其中生成一个名为`input_log.txt`的log文件。同时,会启动一个子线程,动态地显示log文件的内容。主线程每秒钟随机生成一个0-99的整数,并将其记录到log文件中。每次记录都会添加时间戳,并且不会覆盖之前的记录。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)