Untitled
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
#include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> extern char **environ; /* int _getenv(char *key) { char *token; unsigned int i = 0; for (i = 0; environ[i]; i++) { token = strtok(environ[i], "="); if (strcmp(key, token) == 0) return (1); } return (0); } */ int len_environ(char **env) { int i = 0; while (env[i]) i++; return (i); } int _setenv(char *key, char *value, int overwrite) { char *new_token; size_t len_key, len_value; int len_env, i = 0, found = 0; char **new_environ; if (key == NULL || value == NULL) return (-1); if (getenv(key) && overwrite == 0) return (0); len_key = strlen(key); len_value = strlen(value); new_token = malloc(sizeof(char) * (len_value + len_key + 2)); strcpy(new_token, key); strcat(new_token, "="); strcat(new_token, value); new_token[len_key + len_value + 1] = '\0'; len_env = len_environ(environ); if (getenv(key)) new_environ = malloc(sizeof(char *) * len_env); else new_environ = malloc(sizeof(char *) * len_env + 1); while (environ[i]) { if (strncmp(environ[i], key, strlen(key)) == 0) { new_environ[i] = strdup(new_token); found = 1; } else new_environ[i] = environ[i]; i++; } if (found == 0) { new_environ[i] = strdup(new_token); new_environ[i + 1] = NULL; } else new_environ[i] = NULL; environ = new_environ; return (0); } int main() { int i = 0; _setenv("PATH", "salam", 0); for (i = 0; environ[i]; i++) printf("%s\n", environ[i]); }