Replace fgets() with agetline()

This commit is contained in:
sin 2014-06-14 13:13:10 +01:00
parent 191cc71cee
commit 816199471f
3 changed files with 15 additions and 7 deletions

View File

@ -2,6 +2,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "text.h"
#include "util.h"
static void parse_modline(char *buf, char **name, char **size,
@ -18,8 +19,9 @@ main(int argc, char *argv[])
{
const char *modfile = "/proc/modules";
FILE *fp;
char buf[BUFSIZ];
char *buf = NULL;
char *name, *size, *refcount, *users;
size_t bufsize = 0;
size_t len;
ARGBEGIN {
@ -35,7 +37,7 @@ main(int argc, char *argv[])
fp = fopen(modfile, "r");
if (!fp)
eprintf("fopen %s:", modfile);
while (fgets(buf, sizeof buf, fp)) {
while (agetline(&buf, &bufsize, fp) != -1) {
parse_modline(buf, &name, &size, &refcount, &users);
if (!name || !size || !refcount || !users)
eprintf("invalid format: %s\n", modfile);
@ -47,6 +49,7 @@ main(int argc, char *argv[])
}
if (ferror(fp))
eprintf("%s: read error:", modfile);
free(buf);
fclose(fp);
return EXIT_SUCCESS;
}

View File

@ -2,6 +2,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "text.h"
#include "util.h"
static void lsusb(const char *file);
@ -30,7 +31,8 @@ lsusb(const char *file)
FILE *fp;
char *cwd;
char path[PATH_MAX];
char buf[BUFSIZ];
char *buf = NULL;
size_t size = 0;
unsigned int i = 0, busnum = 0, devnum = 0, pid = 0, vid = 0;
cwd = agetcwd();
@ -38,7 +40,7 @@ lsusb(const char *file)
free(cwd);
if (!(fp = fopen(path, "r")))
return;
while (fgets(buf, sizeof(buf), fp)) {
while (agetline(&buf, &size, fp) != -1) {
if (sscanf(buf, "BUSNUM=%u\n", &busnum) ||
sscanf(buf, "DEVNUM=%u\n", &devnum) ||
sscanf(buf, "PRODUCT=%x/%x/", &pid, &vid))
@ -51,6 +53,6 @@ lsusb(const char *file)
}
if (ferror(fp))
eprintf("%s: read error:", path);
free(buf);
fclose(fp);
}

View File

@ -5,6 +5,7 @@
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "text.h"
#include "util.h"
static void
@ -160,8 +161,9 @@ int
main(int argc, char *argv[])
{
FILE *fp;
char buf[BUFSIZ], *p;
char *buf = NULL, *p;
char *file = NULL;
size_t size = 0;
int i;
int r = EXIT_SUCCESS;
@ -184,7 +186,7 @@ main(int argc, char *argv[])
fp = fopen(file, "r");
if (!fp)
eprintf("fopen %s:", file);
while (fgets(buf, sizeof(buf), fp)) {
while (agetline(&buf, &size, fp) != -1) {
p = buf;
for (p = buf; *p == ' ' || *p == '\t'; p++)
;
@ -202,6 +204,7 @@ main(int argc, char *argv[])
}
if (ferror(fp))
eprintf("%s: read error:", file);
free(buf);
fclose(fp);
}