#define MAX_LINE_LENGTH 1024 #define MAX_RECORDS 5 char command[] = "/usr/bin/sn_core.elf getstat 2>/dev/null"; char line[MAX_LINE_LENGTH]; const char *filename = "data.txt"; float temp; char *Temp[MAX_RECORDS] = {0}; int index = 0; void parse_temperature(char *line) { char *temp_str; char *token; // 解析温度 if ((temp_str = strstr(line, "temp: ")) != NULL) { temp_str += strlen("temp: "); temp = strtof(temp_str, NULL); } } void add_record(float temp) { if (index >= MAX_RECORDS) { free(Temp[0]); memmove(Temp, Temp + 1, (MAX_RECORDS - 1) * sizeof(char *)); index--; } Temp[index] = malloc(sizeof(float)); memcpy(Temp[index], &temp, sizeof(float)); index++; } void print_records() { for (int i = 0; i < index; i++) { printf("%f\n", *((float *)Temp[i])); } } int main() { FILE *fp,*fd; while (1) { fp = popen(command, "r"); if(fp == NULL){ printf("Error running command.\n"); exit(1); } fd = fopen(filename,"w"); if(fd == NULL){ printf("Error open file!\n"); exit(1); } while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) { //printf("%s\n",line); parse_temperature(line); } pclose(fp); add_record(temp); //print_records(); sleep(1); } return 0; } 优化代码 并将Temp[]数组里的值写入data.text文本中
时间: 2024-03-27 13:38:53 浏览: 128
以下是对代码的优化,并将Temp[]数组里的值写入data.txt文本中的修改:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_LINE_LENGTH 1024
#define MAX_RECORDS 5
char command[] = "/usr/bin/sn_core.elf getstat 2>/dev/null";
char line[MAX_LINE_LENGTH];
const char *filename = "data.txt";
float temp;
float *Temp[MAX_RECORDS] = {0};
int index = 0;
void parse_temperature(char *line) {
char *temp_str;
// 解析温度
if ((temp_str = strstr(line, "temp: ")) != NULL) {
temp_str += strlen("temp: ");
temp = strtof(temp_str, NULL);
}
}
void add_record(float temp) {
if (index >= MAX_RECORDS) {
free(Temp[0]);
memmove(Temp, Temp + 1, (MAX_RECORDS - 1) * sizeof(float *));
index--;
}
Temp[index] = malloc(sizeof(float));
memcpy(Temp[index], &temp, sizeof(float));
index++;
}
void print_records() {
FILE *fd = fopen(filename,"w");
if(fd == NULL){
printf("Error open file!\n");
exit(1);
}
for (int i = 0; i < index; i++) {
fprintf(fd, "%f\n", *(Temp[i]));
}
fclose(fd);
}
int main() {
while (1) {
FILE *fp = popen(command, "r");
if(fp == NULL){
printf("Error running command.\n");
exit(1);
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
//printf("%s\n",line);
parse_temperature(line);
}
pclose(fp);
add_record(temp);
print_records();
sleep(1);
}
return 0;
}
```
对代码进行的优化包括:
1. 将Temp数组的类型从`char *`改为`float *`,使其更符合实际存储的数据类型;
2. 将文件操作放在`print_records`函数中进行,使得代码更加模块化和可读性更高;
3. 在打开文件时检查是否成功打开,避免出现文件操作错误导致程序异常退出。
阅读全文