RInside Version 0.2.16
setenv.c
Go to the documentation of this file.
1 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
2 //
3 // RInside.cpp: R/C++ interface class library -- Easier R embedding into C++
4 //
5 // Copyright (C) 2009 - 2010 Dirk Eddelbuettel and Richard Holbrey
6 // Copyright (C) 2012 Dirk Eddelbuettel and Romain Francois
7 //
8 // This file is part of RInside.
9 //
10 // RInside is free software: you can redistribute it and/or modify it
11 // under the terms of the GNU General Public License as published by
12 // the Free Software Foundation, either version 2 of the License, or
13 // (at your option) any later version.
14 //
15 // RInside is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with RInside. If not, see <http://www.gnu.org/licenses/>.
22 
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 
27 // borrowed from Renviron.c
28 extern "C" int setenv(const char *env_var, const char *env_val, int dummy) {
29  char *buf, *value, *p, *q, *a, *b, quote='\0';
30  int inquote = 0;
31 
32  //make non-const copies
33  a = (char *) malloc((strlen(env_var) + 1) * sizeof(char));
34  b = (char *) malloc((strlen(env_val) + 1) * sizeof(char));
35  if (!a || !b) {
36  Rf_error("memory allocation failure in setenv");
37  }
38  strcpy(a, env_var);
39  strcpy(b, env_val);
40 
41  buf = (char *) malloc((strlen(a) + strlen(b) + 2) * sizeof(char));
42  if (!buf) {
43  Rf_error("memory allocation failure in setenv");
44  }
45  strcpy(buf, a); strcat(buf, "=");
46  value = buf+strlen(buf);
47 
48  /* now process the value */
49  for(p = b, q = value; *p; p++) {
50  /* remove quotes around sections, preserve \ inside quotes */
51  if(!inquote && (*p == '"' || *p == '\'')) {
52  inquote = 1;
53  quote = *p;
54  continue;
55  }
56 
57  if(inquote && *p == quote && *(p-1) != '\\') {
58  inquote = 0;
59  continue;
60  }
61 
62  if(!inquote && *p == '\\') {
63  if(*(p+1) == '\n') {
64  p++;
65  }
66  else if(*(p+1) == '\\') {
67  *q++ = '/';
68  p++;
69  }
70  else {
71  *q++ = '/';
72  }
73  continue;
74  }
75 
76  if(inquote && *p == '\\' && *(p+1) == quote)
77  continue;
78  *q++ = *p;
79  }
80  *q = '\0';
81  //if (putenv(buf))
82  //warningcall(R_NilValue, _("problem in setting variable '%s' in Renviron"), a);
83  return putenv(buf);
84 
85  /* no free here: storage remains in use */
86 }
87 
int setenv(const char *env_var, const char *env_val, int dummy)
Definition: setenv.c:28