Raspberry Pi c to get Raspberry Pi CPU temperature

C language file IO operation
    Create a new file named cpu-temp.c, the specific content of the file is as follows:
#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define TEMP_PATH "/sys/class/thermal/thermal_zone0/temp"
#define MAX_SIZE 32
int main(void)
{
    int fd;
    double temp = 0;
    char buf[MAX_SIZE];
    
    // 打开/sys/class/thermal/thermal_zone0/temp
    fd = open(TEMP_PATH, O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "failed to open thermal_zone0/temp\n");
        return -1;
    }
    
    // read content
    if (read(fd, buf, MAX_SIZE) < 0) {
        fprintf(stderr, "failed to read temp\n");
        return -1;
    }
    
    // Convert to float and print
    temp = atoi(buf) / 1000.0;
    printf("temp: %.2f\n", temp);
    
    // close the file
    close(fd);
}


Enter the following command in the cpu-temp.c directory to generate an executable file, and then execute the file.
quote
# Compile and link
gcc -o test cpu-temp.c
# Execute
./test
# Execute returns
temp: 49.2



C appears warning: implicit declaration of function 'read' [-Wimplicit-function-declaration] This problem

Solution :
first execute the following command to see which header file read is under
quote
man read

Add the header file compilation, the problem is solved
quote
#include <unistd.h>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326219923&siteId=291194637