Get shell variable from C

2

This is the code I was testing, but for some reason the output I get is nothing.

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

int main (int argc,char*argv[], char *envp[]){
    FILE *fp;
    char path[1035];
    fp=popen("/bin/echo ${COLUMNS}","r");
    if (fp==NULL){
        printf("hubo un error");
        return 1;
    }

    while (fgets(path,sizeof(path)-1,fp)){
        printf("%s",path);
    }

    pclose(fp);
    return 0;

}

The question is:

How do I get the shell variable $ COLUMNS in c language, by linux ?, or what I'm missing or am I doing wrong?

I appreciate your interest

    
asked by Agustn C. M. R. 28.04.2017 в 19:31
source

1 answer

2

Use getenv( ) :

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

int main( void ) {
  printf( "%s\n", getenv( "COLUMNS" ) );

  return 0;
}

char *getenv( const char *name ) is available from C89. Returns NULL if the variable in question is not defined.

Notice that it returns a char * , that you will have to convert to what you need; in your case, to an integer:

int ancho;
char *buff = getenv( "COLUMNS" );

if( buff )
  ancho = atoi( buff );
    
answered by 28.04.2017 в 19:36