简体   繁体   中英

How can I implement "export" command in C?

I am writing a project that implementing "shell" with some commands and I am struggling with the "export" command. When I use export command it prints some variables. But I don know how can get that info's with C.

The portable POSIX way to traverse the environment is through the global variable environ , which works like argv but is for environment variables. It stores strings of the form foo=bar , where foo is an environment variable and bar is its assigned value.

In general, you should not modify the strings nor what strings are pointed to, hence I've const ified the declaration below, but conventionally it's typed as char** .

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>

extern const char *const *const environ;
int main(void) {
        for(size_t i = 0; environ[i]; i++) {
                if(puts(environ[i]) == EOF) {
                        perror("Failed to print environment variable");
                        exit(EXIT_FAILURE);
                }
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM