git: 6193855fc76c - main - sysctl: Refactor function parsefile()

From: Zhenlei Huang <zlei_at_FreeBSD.org>
Date: Thu, 30 Jan 2025 18:23:02 UTC
The branch main has been updated by zlei:

URL: https://cgit.FreeBSD.org/src/commit/?id=6193855fc76c591ffabe6168cd674e6ec0dafa8e

commit 6193855fc76c591ffabe6168cd674e6ec0dafa8e
Author:     Zhenlei Huang <zlei@FreeBSD.org>
AuthorDate: 2025-01-30 18:20:41 +0000
Commit:     Zhenlei Huang <zlei@FreeBSD.org>
CommitDate: 2025-01-30 18:20:41 +0000

    sysctl: Refactor function parsefile()
    
    Let the caller open the file and pass in the file handler. This can
    benefit an upcoming change so that we will have cleaner logic.
    
    No functional change intended.
    
    Suggested by:   markj
    MFC after:      1 week
---
 sbin/sysctl/sysctl.c | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)

diff --git a/sbin/sysctl/sysctl.c b/sbin/sysctl/sysctl.c
index d3a3c64057d3..200c2da8850f 100644
--- a/sbin/sysctl/sysctl.c
+++ b/sbin/sysctl/sysctl.c
@@ -66,7 +66,7 @@ static int	Nflag, nflag, oflag, qflag, tflag, Tflag, Wflag, xflag;
 static bool	Fflag, Jflag, lflag, Vflag;
 
 static int	oidfmt(int *, int, char *, u_int *);
-static int	parsefile(const char *);
+static int	parsefile(FILE *);
 static int	parse(const char *, int);
 static int	show_var(int *, int, bool);
 static int	sysctl_all(int *, int);
@@ -131,6 +131,7 @@ main(int argc, char **argv)
 {
 	int ch;
 	int warncount = 0;
+	FILE *file = NULL;
 
 	setlocale(LC_NUMERIC, "");
 	setbuf(stdout,0);
@@ -226,8 +227,13 @@ main(int argc, char **argv)
 	if (argc == 0 && conffile == NULL)
 		usage();
 
-	if (conffile != NULL)
-		warncount += parsefile(conffile);
+	if (conffile != NULL) {
+		file = fopen(conffile, "r");
+		if (file == NULL)
+			err(EX_NOINPUT, "%s", conffile);
+		warncount += parsefile(file);
+		fclose(file);
+	}
 
 	while (argc-- > 0)
 		warncount += parse(*argv++, 0);
@@ -568,15 +574,11 @@ parse(const char *string, int lineno)
 }
 
 static int
-parsefile(const char *filename)
+parsefile(FILE *file)
 {
-	FILE *file;
 	char line[BUFSIZ], *p, *pq, *pdq;
 	int warncount = 0, lineno = 0;
 
-	file = fopen(filename, "r");
-	if (file == NULL)
-		err(EX_NOINPUT, "%s", filename);
 	while (fgets(line, sizeof(line), file) != NULL) {
 		lineno++;
 		p = line;
@@ -612,7 +614,6 @@ parsefile(const char *filename)
 		else
 			warncount += parse(p, lineno);
 	}
-	fclose(file);
 
 	return (warncount);
 }