#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); for(int i=0;i<MAX_RECORDS;i++){ fprintf(fd,"%s\n",Temp[i]); } //print_records(); sleep(1); } return 0; } 优化代码
时间: 2024-03-27 15:38:30 浏览: 57
C++ 中pragma once 与 #ifndef _XXX_H_ #define _XXX_H_的区别
下面是经过优化的代码,主要是对部分变量进行了重命名,并且使用了更安全的动态内存分配函数:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_LINE_LENGTH 1024
#define MAX_RECORDS 5
const char *command = "/usr/bin/sn_core.elf getstat 2>/dev/null";
const char *filename = "data.txt";
float temperature;
char *temperature_records[MAX_RECORDS] = {NULL};
int record_count = 0;
void parse_temperature(char *line) {
char *temp_str;
char *token;
// 解析温度
if ((temp_str = strstr(line, "temp: ")) != NULL) {
temp_str += strlen("temp: ");
temperature = strtof(temp_str, NULL);
}
}
void add_temperature_record(float temperature) {
if (record_count >= MAX_RECORDS) {
free(temperature_records[0]);
memmove(temperature_records, temperature_records + 1, (MAX_RECORDS - 1) * sizeof(char *));
record_count--;
}
temperature_records[record_count] = (char *)malloc(sizeof(float));
memcpy(temperature_records[record_count], &temperature, sizeof(float));
record_count++;
}
void print_temperature_records() {
for (int i = 0; i < record_count; i++) {
printf("%f\n", *((float *)temperature_records[i]));
}
}
int main() {
FILE *pipe, *file;
while (1) {
pipe = popen(command, "r");
if (pipe == NULL) {
printf("Error running command.\n");
exit(1);
}
file = fopen(filename, "w");
if (file == NULL) {
printf("Error open file!\n");
exit(1);
}
char line[MAX_LINE_LENGTH];
while (fgets(line, MAX_LINE_LENGTH, pipe) != NULL) {
parse_temperature(line);
}
pclose(pipe);
add_temperature_record(temperature);
for (int i = 0; i < record_count; i++) {
fprintf(file, "%s\n", temperature_records[i]);
}
sleep(1);
}
return 0;
}
```
阅读全文