x*: fixing whitespaces
[transsip.git] / src / xutils.c
blob27b638321f473c7171439568bbc239aa74f39407
1 /*
2 * transsip - the telephony toolkit
3 * By Daniel Borkmann <daniel@transsip.org>
4 * Copyright 2011, 2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
5 * Swiss federal institute of technology (ETH Zurich)
6 * Subject to the GPL, version 2.
7 */
9 #define _BSD_SOURCE
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <stdarg.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/socket.h>
24 #include "xutils.h"
25 #include "xmalloc.h"
26 #include "die.h"
28 int open_or_die(const char *file, int flags)
30 int ret = open(file, flags);
31 if (ret < 0)
32 panic("Open error!!\n");
34 return ret;
37 int open_or_die_m(const char *file, int flags, mode_t mode)
39 int ret = open(file, flags, mode);
40 if (ret < 0)
41 panic("Open error!!\n");
43 return ret;
46 ssize_t read_or_die(int fd, void *buf, size_t len)
48 ssize_t ret = read(fd, buf, len);
49 if (ret < 0) {
50 if (errno == EPIPE)
51 exit(EXIT_SUCCESS);
52 panic("Read error!!\n");
55 return ret;
58 ssize_t write_or_die(int fd, const void *buf, size_t len)
60 ssize_t ret = write(fd, buf, len);
61 if (ret < 0) {
62 if (errno == EPIPE)
63 exit(EXIT_SUCCESS);
64 panic("Write error!!\n");
67 return ret;
70 size_t strlcpy(char *dest, const char *src, size_t size)
72 size_t ret = strlen(src);
73 if (size) {
74 size_t len = (ret >= size) ? size - 1 : ret;
76 memcpy(dest, src, len);
77 dest[len] = '\0';
80 return ret;
83 int slprintf(char *dst, size_t size, const char *fmt, ...)
85 int ret;
86 va_list ap;
88 va_start(ap, fmt);
89 ret = vsnprintf(dst, size, fmt, ap);
90 dst[size - 1] = '\0';
91 va_end(ap);
93 return ret;
96 char **strntoargv(char *str, size_t len, int *argc)
98 int done = 0;
99 char **argv = NULL;
101 if (argc == NULL)
102 panic("argc is null!\n");
103 *argc = 0;
104 if (len <= 1) /* '\0' */
105 goto out;
106 while (!done) {
107 while (len > 0 && *str == ' ') {
108 len--;
109 str++;
111 if (len > 0 && *str != '\0') {
112 (*argc)++;
113 argv = xrealloc(argv, 1, sizeof(char *) * (*argc));
114 argv[(*argc) - 1] = str;
115 while (len > 0 && *str != ' ') {
116 len--;
117 str++;
119 if (len > 0 && *str == ' ') {
120 len--;
121 *str = '\0';
122 str++;
124 } else {
125 done = 1;
128 out:
129 return argv;