mirror of
https://github.com/troglobit/finit.git
synced 2026-10-01 05:22:48 +07:00
New functions: fnread() and fngetint(), companions to fnwrite()
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
+44
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user