Handle errors in fscanf and fread. - energy - measure energy usage | |
git clone git://bitreich.org/energy git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws… | |
Log | |
Files | |
Refs | |
Tags | |
README | |
LICENSE | |
--- | |
commit 3b9da8cb1c2fcacd4570f25d02194124e526caa2 | |
parent 94c96ddd16d2012cdaaef649903e8fcc663a9296 | |
Author: Christoph Lohmann <[email protected]> | |
Date: Thu, 24 Aug 2023 15:24:43 +0200 | |
Handle errors in fscanf and fread. | |
Diffstat: | |
M energy.c | 10 ++++++++-- | |
1 file changed, 8 insertions(+), 2 deletions(-) | |
--- | |
diff --git a/energy.c b/energy.c | |
@@ -55,7 +55,10 @@ long long_from_file(const char *fname) { | |
return -1; | |
} else { | |
long x; | |
- fscanf(f, "%ld", &x); | |
+ if (fscanf(f, "%ld", &x) < 0) { | |
+ fprintf(stderr, "%s: %s\n", fname, strerror(errno)); | |
+ return -1; | |
+ } | |
fclose(f); | |
return x; | |
} | |
@@ -118,7 +121,10 @@ void sensor_battery(void) { | |
} | |
} else { | |
char buf[128]; | |
- fread(buf, 1, sizeof(buf), f); | |
+ if (fread(buf, 1, sizeof(buf), f) < 1) { | |
+ fprintf(stderr, "%s: %s\n", battery_status, strerror(errno)); | |
+ return; | |
+ } | |
const char discharging[] = "Discharging"; | |
// Measurement of battery discharge is only meaningful if the | |
// battery is actually discharging. |