Public
Snippet $1655242 authored by Jesse

Display the temperature of a Raspberry Pi that is running Raspbian

Edited
raspbiantemp.cpp
/*\
 * File: raspbiantemp.cpp
 * Language: C++
 * Version: 0
 * Author: culb (nightfrog)
 * Contact: the01culb[at]gmail[dot]com
 *
 * Compile:
 *  clang++ -Wall -Wextra -O3 -std=c++11 raspbiantemp.cpp -o pitemp
 *  g++ -Wall -Wextra -O3 -std=c++11 raspbiantemp.cpp -o pitemp
 *
 * Note: Tested with Raspberry Pi 3 model B using clang 3.5 and gcc 4.9
 *
 * License:
 *  If this code is used in any way then
 *  be courteous and include all of my information and notes
\*/
 
#include <ios>     /* fixed */
#include <locale>  /* ::isdigit */
#include <string>  /* string, stof */
#include <iomanip> /* setprecision */
#include <fstream>
#include <iostream>
#include <algorithm> /* all_of */
 
auto main() -> int
{
    std::ifstream file;
 
    file.open( "/sys/class/thermal/thermal_zone0/temp" );
 
    if( file.is_open() )
    {
        std::string line;
        float celsius = 0.0;
 
        while( std::getline( file, line ) )
        {
            /* Check if line is all digits */
            if( [ &line ](){ return std::all_of( line.begin(), line.end(), ::isdigit ); }() )
            {
                celsius = std::stof( line );
                file.close();
            }
        }
 
        if( celsius )
        {
            std::cout << std::fixed << std::setprecision( 2 )
                    << celsius / 1000 << "C" /* Celcius */
                    << "/"
                    << ( celsius / 1000 ) * 9 / 5 + 32 << "F" /* Fahrenheit */
                    << std::endl;
 
            return( EXIT_SUCCESS );
        }
    }
 
    /* Something failed */
    return( EXIT_FAILURE );
}