File: util.c

package info (click to toggle)
netdiag 1.2-1
  • links: PTS
  • area: main
  • in suites: buster, sid
  • size: 3,268 kB
  • sloc: ansic: 23,895; sh: 5,544; makefile: 328; awk: 130
file content (128 lines) | stat: -rw-r--r-- 2,001 bytes parent folder | download | duplicates (5)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
 *	Copyright (c) 2004 Rinet Corp., Novosibirsk, Russia
 *
 * Redistribution and use in source forms, with and without modification,
 * are permitted provided that this entire comment appears intact.
 *
 * THIS SOURCE CODE IS PROVIDED ``AS IS'' WITHOUT ANY WARRANTIES OF ANY KIND.
 */

#ifdef	HAVE_CONFIG_H
#include <config.h>
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "util.h"

char *
strip_path(path)
	const char *path;
{
	char *cp;
	if (path && (cp = strrchr(path, '/')) != 0)
		return (++cp);
	return (char *)path;
}

char *
strip_blanks(str)
	char *str;
{
	char *bp, *ep;

	if (!str || !*str)
		return str;

	bp = str;
	while (*bp == ' ' || *bp == '\t') bp++;

	ep = bp + (strlen(bp)-1);
	while (ep >= bp &&
	       (*ep == ' ' || *ep == '\t' || *ep == '\r' || *ep == '\n'))
		*ep-- = '\0';

	return bp;
}

/*
 * Copy arg vector into a new buffer, concatenating arguments with spaces.
 */
char *
copy_argv(av)
	char **av;
{
	unsigned int len = 0;
	char **p, *buf, *src, *dst;

	p = av;
	if (*p == 0) return 0;
	while (*p) len += strlen(*p++) + 1;
	if ((buf = (char *)malloc(len)) == 0) {
		perror("malloc");
		return 0;
	}
	p = av;
	dst = buf;
	while ((src = *p++) != 0) {
		while ((*dst++ = *src++) != '\0');
		dst[-1] = ' ';
	}
	dst[-1] = '\0';

	return buf;
}

/*
 * Return size in bytes of regular file `name'.
 */
long
fd_size(fd)
	int fd;
{
	struct stat st;
	if (fstat(fd, &st) < 0)
		return -1;
	return (long)st.st_size;
}

char *
load_file(name)
	const char *name;
{
	int fd;
	long sz;
	char *cp;

	if ((fd = open(name, O_RDONLY)) < 0) {
		perror(name);
		return 0;
	}
	if ((sz = fd_size(fd)) < 0) {
		perror(name);
		close(fd);
		return 0;
	}
	if ((cp = (char *)malloc(sz + 1)) == 0) {
		perror(name);
		close(fd);
		return 0;
	}
	if ((sz = read(fd, cp, sz)) < 0) {
		perror(name);
		close(fd);
		free(cp);
		return 0;
	}
	close(fd);
	cp[sz] = '\0';

	return cp;
}