You can write a Variadic Function
able to receive a string de formatação
" as an argument, enabling manipulation of all primitive types by default, see:
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#define CMD_TAM_MAX (1024)
int systemf( const char * fmt, ... )
{
va_list args;
char cmd[ CMD_TAM_MAX + 1 ];
va_start( args, fmt );
vsnprintf( cmd, CMD_TAM_MAX + 1, fmt, args );
va_end(args);
return system(cmd);
}
int main( void )
{
int i = 123;
char ch = 'X';
char * txt = "Ola Mundo!";
float pi = 3.1415f;
double dbl = 1234567890L;
systemf( "echo int: %d", i );
systemf( "echo char: %c", ch );
systemf( "echo char*: %s", txt );
systemf( "echo float: %f", pi );
systemf( "echo double: %f", dbl );
return 0;
}
Output:
int: 123
char: X
char*: Ola Mundo!
float: 3.141500
double: 1234567890.000000
See working at Ideone.com
To access the variáveis de ambiente
of your shell , you can use a main()
with a slightly different signature than usual:
int main( int argc, char **argv, char **envp );
Where char ** envp
is the list of all variáveis de ambiente
available, in VARIAVEL=VALOR
format, with a NULL
terminator indicating the end, see:
#include <stdlib.h>
int main( int argc, char **argv, char **envp )
{
char **env = NULL;
for( env = envp; *env != NULL; env++ )
{
char * variavel = *env;
printf( "%s\n", variavel );
}
return 0;
}
Output:
LANG=en_US.UTF-8
WORKSPACE=/tmp/a4a2fff3-ba98-4fda-9d1d-e31d83ac61ee
PWD=/home/0NxZg3
HOME=/home/0NxZg3
TMPDIR=/tmp/WpSkY2
TMPDIR_GLOBAL=/tmp/a4a2fff3-ba98-4fda-9d1d-e31d83ac61ee
SHLVL=0
PATH=/usr/local/bin:/usr/bin:/bin
See working at Ideone.com
To access a specific variavel de ambiente
within your program, you can use the getenv()
function. from the default library stdlib.h
, see:
char * valor = getenv("PATH");
printf( "PATH=%s\n", valor );