summaryrefslogtreecommitdiffabout
path: root/lib/split3.c
blob: e7e8c858f51bbcf2f2ddb9ddb0798925fab74cf2 (plain)
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
/* This file is part of GNU Pies.
   Copyright (C) 2007, 2008, 2009, 2010, 2013 Sergey Poznyakoff

   GNU Pies is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   GNU Pies is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Pies.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "libpies.h"

static int
split3 (const char *input, char *res[3], int flag)
{
  size_t len;
  char *p;

  p = strchr (input, ' ');
  if (!p)
    return 1;

  len = p - input;
  res[0] = malloc (len + 1);
  if (!res[0])
    return -1;
  memcpy (res[0], input, len);
  res[0][len] = 0;

  input = p + 1;

  p = (flag ? strrchr : strchr) (input, ' ');

  if (!p)
    return 1;

  len = p - input;
  res[1] = malloc (len + 1);
  if (!res[1])
    return -1;
  memcpy (res[1], input, len);
  res[1][len] = 0;
  
  res[2] = strdup (p + 1);
  if (!res[2])
    return -1;

  return 0;
}

int
strsplit3 (const char *input, char *result[3], int flag)
{
  char *tmp[3] = { NULL, NULL, NULL };
  int rc = split3 (input, tmp, flag);
  if (rc)
    {
      int ec = errno;
      free (tmp[0]);
      free (tmp[1]);
      free (tmp[2]);
      errno = ec;
    }
  else
    {
      result[0] = tmp[0];
      result[1] = tmp[1];
      result[2] = tmp[2];
    }
  return rc;
}

Return to:

Send suggestions and report system problems to the System administrator.