confd: Add helpers to read files containing a single number

This commit is contained in:
Tobias Waldekranz
2023-05-12 14:24:41 +02:00
committed by Joachim Wiberg
parent 751b22f4db
commit 35ec76b0ef
2 changed files with 60 additions and 0 deletions
+54
View File
@@ -48,6 +48,60 @@ static FILE *open_file(const char *mode, const char *fmt, va_list ap)
return fopen(file, mode);
}
int vreadllf(long long *value, const char *fmt, va_list ap)
{
char line[0x100];
FILE *fp;
fp = open_file("r", fmt, ap);
if (!fp)
return -1;
if (!fgets(line, sizeof(line), fp)) {
fclose(fp);
return -1;
}
fclose(fp);
errno = 0;
*value = strtoll(line, NULL, 0);
return errno ? -1 : 0;
}
int readllf(long long *value, const char *fmt, ...)
{
va_list ap;
int rc;
va_start(ap, fmt);
rc = vreadllf(value, fmt, ap);
va_end(ap);
return rc;
}
int readdf(int *value, const char *fmt, ...)
{
long long tmp;
va_list ap;
int rc;
va_start(ap, fmt);
rc = vreadllf(&tmp, fmt, ap);
va_end(ap);
if (rc)
return rc;
if (tmp < INT_MIN || tmp > INT_MAX)
return -1;
*value = tmp;
return 0;
}
/*
* Write interger value to a file composed from fmt and optional args.
*/
+6
View File
@@ -6,6 +6,12 @@
FILE *popenf(const char *type, const char *cmdf, ...)
__attribute__ ((format (printf, 2, 3)));
int vreadllf(long long *value, const char *fmt, va_list ap);
int readllf(long long *value, const char *fmt, ...)
__attribute__ ((format (printf, 2, 3)));
int readdf(int *value, const char *fmt, ...)
__attribute__ ((format (printf, 2, 3)));
int writedf(int value, const char *fmt, ...)
__attribute__ ((format (printf, 2, 3)));
int writesf(const char *str, const char *fmt, ...)