aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorRob Landley <rob@landley.net>2007-11-29 17:49:50 -0600
committerRob Landley <rob@landley.net>2007-11-29 17:49:50 -0600
commit7634b55f27ad483ec634ba9defac93872e3a329f (patch)
tree5d1a64072f77577d2d231d91872a1195ba0fd9c9 /lib
parentf7bb55bb14128a2b9367e2e089e9930c456f801f (diff)
downloadtoybox-7634b55f27ad483ec634ba9defac93872e3a329f.tar.gz
Add loopfiles() function, make catv use it.
Diffstat (limited to 'lib')
-rw-r--r--lib/lib.c23
-rw-r--r--lib/lib.h1
2 files changed, 24 insertions, 0 deletions
diff --git a/lib/lib.c b/lib/lib.c
index 5d01efc9..6aaf7b00 100644
--- a/lib/lib.c
+++ b/lib/lib.c
@@ -545,3 +545,26 @@ void xpidfile(char *name)
xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
close(fd);
}
+
+// Iterate through an array of files, opening each one (read only) and
+// calling a function on that filehandle and name. The special filename
+// "-" means stdin. An empty argument list calls function() on stdin.
+void loopfiles(char **argv, void (*function)(int fd, char *name))
+{
+ int fd;
+
+ // If no arguments, read from stdin.
+ if (!*argv) function(0, *argv);
+ else do {
+ // Filename "-" means read from stdin.
+ // Inability to open a file prints a warning, but doesn't exit.
+
+ if (!strcmp(*argv,"-")) fd=0;
+ else if (0>(fd = open(*argv, O_RDONLY))) {
+ perror_msg("%s",*argv);
+ toys.exitval = 1;
+ }
+ function(fd, *argv);
+ close(fd);
+ } while (*++argv);
+}
diff --git a/lib/lib.h b/lib/lib.h
index 67c6dac9..963abb68 100644
--- a/lib/lib.h
+++ b/lib/lib.h
@@ -73,6 +73,7 @@ char *itoa(int n);
long atolx(char *c);
off_t fdlength(int fd);
char *xreadlink(char *name);
+void loopfiles(char **argv, void (*function)(int fd, char *name));
// getmountlist.c
struct mtab_list {