New functions: fnread() and fngetint(), companions to fnwrite()

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg
2021-05-11 07:02:30 +02:00
parent 21ebbb942f
commit cbb8935660
2 changed files with 46 additions and 0 deletions
+44
View File
@@ -154,6 +154,35 @@ char *str(char *fmt, ...)
return buf;
}
int fnread(char *buf, size_t len, char *fmt, ...)
{
char path[256];
va_list ap;
FILE *fp;
va_start(ap, fmt);
vsnprintf(path, sizeof(path), fmt, ap);
va_end(ap);
if (!buf || !len) {
struct stat st;
if (stat(path, &st))
return -1;
return (ssize_t)st.st_size;
}
fp = fopen(path, "r");
if (!fp)
return -1;
len = fread(buf, sizeof(char), len, fp);
fclose(fp);
return (int)len;
}
int fnwrite(char *value, char *fmt, ...)
{
char path[256];
@@ -185,6 +214,21 @@ int fnwrite(char *value, char *fmt, ...)
return rc;
}
int fngetint(char *path, int *val)
{
char buf[10];
if (fnread(buf, sizeof(buf), path) <= 0)
return -1;
errno = 0;
*val = strtoul(chomp(buf), NULL, 0);
if (errno)
return -1;
return 0;
}
/*
* musl libc default to /dev/null/utmp and /dev/null/wtmp, respectively.
* See https://www.openwall.com/lists/musl/2012/03/04/4 for reasoning.
+2
View File
@@ -50,7 +50,9 @@ extern char *prognm;
char *progname (char *arg0);
char *str (char *fmt, ...);
int fnread (char *buf, size_t len, char *fmt, ...);
int fnwrite (char *value, char *fmt, ...);
int fngetint (char *path, int *val);
int has_utmp (void);
int strtobytes (char *arg);