File: cmdf2argv.c

package info (click to toggle)
dpm-postgres 1.7.4.7-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 13,788 kB
  • ctags: 10,782
  • sloc: ansic: 146,136; sh: 13,362; perl: 11,142; python: 5,529; cpp: 5,113; sql: 1,790; makefile: 955; fortran: 113
file content (82 lines) | stat: -rw-r--r-- 1,541 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * $Id: cmdf2argv.c,v 1.1 2005/04/13 17:00:29 baud Exp $
 */

/*
 * Copyright (C) 1997 by CERN/IT/PDP/DM
 * All rights reserved
 */

#ifndef lint
static char sccsid[] = "@(#)$RCSfile: cmdf2argv.c,v $ $Revision: 1.1 $ $Date: 2005/04/13 17:00:29 $ CERN/IT/PDP/DM Jean-Philippe Baud";
#endif /* not lint */

/*	cmdf2argv - build argv array from a command file */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>

cmdf2argv(cmdfil, argvp)
char *cmdfil;
char ***argvp;
{
	char **argv;
	char *buf;
	int c;
	int cmdfd;
	int n;
	int nargs;
	char *p;
	int parm;
	struct stat st;

	if ((cmdfd = open (cmdfil, O_RDONLY)) < 0) {
		fprintf (stderr, "Command file open error: %s\n", strerror(errno));
		return (-1);
	}
	fstat (cmdfd, &st);
	if (st.st_size == 0) return (0);
	buf = (char *) malloc (st.st_size + 1);
	n = read (cmdfd, buf, st.st_size);
	close (cmdfd);
	*(buf+n) = '\0';
	
	/* 1st pass: count number of args */

	nargs = 0;
	p = buf;
	parm = 0;
	while (c = *p++) {
		if (c == ' ' || c == '\t' || c == '\n') {
			parm = 0;
		} else if (!parm) {
			parm = 1;
			nargs++;
		}
	}
	if (nargs == 0) return (0);
	argv = (char **) malloc ((nargs + 1) * sizeof(char *));

	/* 2nd pass: build argv */

	nargs = 0;
	p = buf;
	parm = 0;
	while (c = *p++) {
		if (c == ' ' || c == '\t' || c == '\n') {
			if (parm) {
				parm = 0;
				*(p - 1) = '\0';
			}
		} else if (!parm) {
			parm = 1;
			argv[nargs++] = p - 1;
		}
	}
	argv[nargs] = NULL;
	*argvp = argv;
	return (nargs);
}