如何读取 Ubuntu 中的电池电量?

How to read the battery level in Ubuntu?

我已经搜索了一段时间如何在没有任何特殊库或任何东西的情况下执行此操作,并且花了一段时间才找到可以正常工作的东西。

可以使用

/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now
/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full

我想知道,在 Ubuntu 18.04 中是否有更好的方法来获取电池状态 使用 C/C++?

万一这个问题没有人回答..这是我的解决方案:

#define PATH_BATT_CHARGE_NOW "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now"
#define PATH_BATT_CHARGE_FULL "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full"


int getBattState(void)
    {
        int chargedPercent = 0;

        FILE *battChargeNow;
        FILE *battChargeFull;
        long unsigned int battMax_mAh = 0;
        long unsigned int battRemain_mAh = 0;

        if (NULL == (battChargeNow = fopen(PATH_BATT_CHARGE_NOW, "r")))
        {
            fclose(battChargeNow);
            return -1;
        }
        if (NULL == (battChargeFull = fopen(PATH_BATT_CHARGE_FULL, "r")))
        {
            fclose(battChargeNow);
            fclose(battChargeFull);
            return -1;
        }

        fscanf((FILE *)battChargeFull, "%lu", &battMax_mAh);
        fscanf((FILE *)battChargeNow, "%lu", &battRemain_mAh);

        chargedPercent = 100.00 * ((float)battRemain_mAh / (float)battMax_mAh);
        return chargedPercent;
    }