linux 读取cpu温度记录到csv文件

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#include <time.h>



FILE* fp = NULL;

void get_cpu_temp()
{
    FILE *fd;
    int temp1, temp2, temp3, temp4, temp5, temp6;
    char buff[256];

    fd = fopen("/sys/class/thermal/thermal_zone0/temp","r");
    fgets(buff,sizeof(buff),fd);
    sscanf(buff, "%d", &temp1);
    fclose(fd);
	printf("cpu1 temp: %d\n", temp1 / 1000);
	
    fd = fopen("/sys/class/thermal/thermal_zone1/temp","r");
    fgets(buff,sizeof(buff),fd);
    sscanf(buff, "%d", &temp2);
    fclose(fd);
	printf("cpu2 temp: %d\n", temp2 / 1000);
	
	fd = fopen("/sys/class/thermal/thermal_zone2/temp","r");
    fgets(buff,sizeof(buff),fd);
    sscanf(buff, "%d", &temp3);
    fclose(fd);
	printf("cpu3 temp: %d\n", temp3 / 1000);
	
	fd = fopen("/sys/class/thermal/thermal_zone3/temp","r");
    fgets(buff,sizeof(buff),fd);
    sscanf(buff, "%d", &temp4);
    fclose(fd);
	printf("cpu4 temp: %d\n", temp4 / 1000);
	
	fd = fopen("/sys/class/thermal/thermal_zone4/temp","r");
    fgets(buff,sizeof(buff),fd);
    sscanf(buff, "%d", &temp5);
    fclose(fd);
	printf("cpu5 temp: %d\n", temp5 / 1000);
	
    fd = fopen("/sys/class/thermal/thermal_zone5/temp","r");
    fgets(buff,sizeof(buff),fd);
    sscanf(buff, "%d", &temp6);
    fclose(fd);
	printf("cpu6 temp: %d\n", temp6 / 1000);
	printf("-------------------------\n");
	
	
	char time[64] = { 0 };
	struct timeval tv;
	int off;
	gettimeofday(&tv, NULL);
	off = strftime(time, sizeof(time), "%H_%M_%S", localtime(&tv.tv_sec));
	snprintf(time + off, sizeof(time) - off, "_%03d", (int)tv.tv_usec / 1000);
	fprintf(fp, "%s,%u,%u,%u,%u,%u,%u,", time, temp1 / 1000, temp2 / 1000, temp3 / 1000, temp4 / 1000, temp5 / 1000, temp6 / 1000);
	fprintf(fp, "\n");
	fflush(fp);
}

int main()
{
	fp = fopen("temp.csv", "w");
    if (!fp)
    {
        printf("Failed to open file temp.csv, error\n");
        return -1;
    }
	
	int ret = fprintf(fp, "time," "cpu1," "cpu2," "cpu3," "cpu4," "cpu5," "cpu6,");
	if (ret < 0)
	{
		printf("Write header to log file failed! error:\n");
		return -1;
	}
	
	fprintf(fp, "\n");

    while(1) {
	
		get_cpu_temp();
		sleep(1);

    }
	
	fclose(fp);

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值