#include #include #include #define CHARGE_NOW_PATH "/sys/class/power_supply/BAT0/charge_now" #define CHARGE_FULL_PATH "/sys/class/power_supply/BAT0/charge_full" #define VERSION "v0.0" #define TITLE "Battery Percentage, by Catluck Kettlemerry" #define PROGNAME "battery_percentage" #define USAGE0 "Usage: " #define USAGE1 "[option]" #define OPTIONS0 "Options:" #define OPTIONS1 "\t-v run verbosely" #define OPTIONS2 "\t-h show help and exit" #define OPTIONS3 "\t-t provide terse output" int run_verbose = 0; int run_terse = 0; void print_help(void){ printf("%s %s\n", TITLE, VERSION); printf("%s %s %s\n", USAGE0, PROGNAME, USAGE1); printf("%s\n%s\n%s\n%s\n", OPTIONS0, OPTIONS1, OPTIONS2, OPTIONS3); } int main(int argc, char *const argv[]){ int opt; while((opt = getopt(argc, argv, "vht")) != -1) { switch(opt){ case 'v': run_verbose = 1; break; case 'h': print_help(); return 0; case 't': run_terse = 1; break; default: printf("Literally how could you pass an unspecified argument to this program"); } } FILE * fd_now = fopen(CHARGE_NOW_PATH, "r"); FILE * fd_full = fopen(CHARGE_FULL_PATH, "r"); int c_now; int c_full; int vals_read = fscanf(fd_now, "%d", &c_now); if(vals_read != 1){ if(errno != 0){ perror("Error reading full battery charge: "); } else if(vals_read == EOF){ printf("End-of-file reached while reading current battery charge(?)"); } else { printf("Invalid number of arguments (%d) returned while reading full battery charge", vals_read); } return 1; } vals_read = fscanf(fd_full, "%d", &c_full); if(vals_read != 1){ if(errno != 0){ perror("Error reading full battery charge: "); } else if(vals_read == EOF){ printf("End-of-file reached while reading full battery charge(?)"); } else { printf("Invalid number of arguments (%d) returned while reading full battery charge", vals_read); } return 1; } if(run_verbose){ printf("Current charge: %d\n", c_now); printf("Full charge: %d\n", c_full); } if(!run_terse) { printf("Battery percentage: "); } float pct = ((float)c_now) / ((float)c_full); printf("%f\n", pct); return 0; }