The Linux Programming Interface

(nextflipdebug5) #1

904 Chapter 44


Listing 44-5: Globbing filename patterns with popen()
––––––––––––––––––––––––––––––––––––––––––––––––––––––– pipes/popen_glob.c
#include <ctype.h>
#include <limits.h>
#include "print_wait_status.h" /* For printWaitStatus() */
#include "tlpi_hdr.h"

q#define POPEN_FMT "/bin/ls -d %s 2> /dev/null"
#define PAT_SIZE 50
#define PCMD_BUF_SIZE (sizeof(POPEN_FMT) + PAT_SIZE)

int
main(int argc, char *argv[])
{
char pat[PAT_SIZE]; /* Pattern for globbing */
char popenCmd[PCMD_BUF_SIZE];
FILE *fp; /* File stream returned by popen() */
Boolean badPattern; /* Invalid characters in 'pat'? */
int len, status, fileCnt, j;
char pathname[PATH_MAX];

for (;;) { /* Read pattern, display results of globbing */
printf("pattern: ");
fflush(stdout);
w if (fgets(pat, PAT_SIZE, stdin) == NULL)
break; /* EOF */
len = strlen(pat);
if (len <= 1) /* Empty line */
continue;

if (pat[len - 1] == '\n') /* Strip trailing newline */
pat[len - 1] = '\0';

/* Ensure that the pattern contains only valid characters,
i.e., letters, digits, underscore, dot, and the shell
globbing characters. (Our definition of valid is more
restrictive than the shell, which permits other characters
to be included in a filename if they are quoted.) */

e for (j = 0, badPattern = FALSE; j < len && !badPattern; j++)
if (!isalnum((unsigned char) pat[j]) &&
strchr("_*?[^-].", pat[j]) == NULL)
badPattern = TRUE;

if (badPattern) {
printf("Bad pattern character: %c\n", pat[j - 1]);
continue;
}

/* Build and execute command to glob 'pat' */

r snprintf(popenCmd, PCMD_BUF_SIZE, POPEN_FMT, pat);
popenCmd[PCMD_BUF_SIZE - 1] = '\0'; /* Ensure string is
null-terminated */
Free download pdf