Henrix
Henrix

Reputation: 29

Print the environment variables WITHOUT VALUES in C

How to print the environment variables in C, but WITHOUT VALUES ?? Only variables.

int main(int argc, char **argv, char **envp)
{
    while(*envp!=NULL) {
        printf("%s\n", *envp);
        envp++;
    }
    system("pause");
    return 0;
}

Upvotes: 0

Views: 619

Answers (2)

Andrzej Budzanowski
Andrzej Budzanowski

Reputation: 1022

Since environmental variables have format of NAME=value you need to display only part of string up to = character.

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv, char **envp)
{
    while(*envp!=NULL) {
        char * len = strchr(*envp, '=');

        if (len == NULL)
            printf("%s\n", *envp);
        else
            printf("%.*s\n", len - *envp, *envp);

        envp++;
    }
    system("pause");
    return 0;
}

Ideone

Upvotes: 2

P.P
P.P

Reputation: 121387

Environment variables are of the form NAME=value. So, you can look for the first = sign and print only upto it to get only the names.

Upvotes: 1

Related Questions