读取AMD笔记本的CPU温度的C++代码
时间: 2024-05-09 16:19:42 浏览: 170
用c++读取txt中的文件显示在电脑上
以下是读取AMD笔记本的CPU温度的C代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_LINE_LENGTH 1024
int main()
{
FILE* fp;
char line[MAX_LINE_LENGTH];
char* token;
const char* delimiter = " ";
const char* search_str = "Tdie";
float temperature = 0;
fp = fopen("/sys/class/hwmon/hwmon0/temp1_input", "r");
if (fp == NULL) {
fprintf(stderr, "Failed to open file\n");
exit(EXIT_FAILURE);
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
token = strtok(line, delimiter);
if (strcmp(token, search_str) == 0) {
token = strtok(NULL, delimiter);
temperature = strtof(token, NULL) / 1000;
break;
}
}
printf("CPU temperature is %.2f degrees Celsius\n", temperature);
fclose(fp);
return 0;
}
```
这段代码打开`/sys/class/hwmon/hwmon0/temp1_input`文件,该文件包含了AMD笔记本的CPU温度信息。然后,它逐行读取该文件并查找包含“Tdie”字符串的行。一旦找到该行,它会解析出温度值并将其打印出来。最后,它关闭文件并退出。
阅读全文