I need to know a way for use environment variables in the C programming language. How can I use and read them?
For example, read an environment variable or take the value of an environment variable and load it in another variable.
You can use following functions -
char * getenv (const char *name)-returns a string that is the value of the environment variable name.
char * secure_getenv (const char *name)
Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
Use the getenv function from stdlib.h. That's it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test\n");
const char* s = getenv("PATH");
// If the environment variable doesn't exist, it returns NULL
printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");
printf("end test\n");
}
getenv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char* my_env_var = getenv("MY_ENV_VAR");
if(my_env_var)
printf("Var found: %s", my_env_var );
else
printf("Var not found.");
return 0;
}
On windows, you would use GetEnvironmentVariable.
#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
TCHAR buff[100] = T("");
DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);
if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
_tprintf(T("USERDOMAIN: %s\n"), buff);
} else if ( resultLengthInCharacters > 100) {
_tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
} else {
// Error handling incomplete, should use GetLastError(),
// but typically:
_tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
}
return 0;
}
But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)
Another way could be to use the global variable environ.
#include <stdio.h>
extern char** environ;
void main(int argc, char* argv[])
{
int i=0;
while(environ[i]!=NULL){
printf("%s\n",environ[i++]);
}
}
Related
I need to know a way for use environment variables in the C programming language. How can I use and read them?
For example, read an environment variable or take the value of an environment variable and load it in another variable.
You can use following functions -
char * getenv (const char *name)-returns a string that is the value of the environment variable name.
char * secure_getenv (const char *name)
Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
Use the getenv function from stdlib.h. That's it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test\n");
const char* s = getenv("PATH");
// If the environment variable doesn't exist, it returns NULL
printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");
printf("end test\n");
}
getenv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char* my_env_var = getenv("MY_ENV_VAR");
if(my_env_var)
printf("Var found: %s", my_env_var );
else
printf("Var not found.");
return 0;
}
On windows, you would use GetEnvironmentVariable.
#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
TCHAR buff[100] = T("");
DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);
if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
_tprintf(T("USERDOMAIN: %s\n"), buff);
} else if ( resultLengthInCharacters > 100) {
_tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
} else {
// Error handling incomplete, should use GetLastError(),
// but typically:
_tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
}
return 0;
}
But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)
Another way could be to use the global variable environ.
#include <stdio.h>
extern char** environ;
void main(int argc, char* argv[])
{
int i=0;
while(environ[i]!=NULL){
printf("%s\n",environ[i++]);
}
}
I'm relatively new to C and cannot figure out why this program seg faults.
It could be a stupid error on my behalf but cannot seem to figure it out.
I also know its unusual using the embedding method I am, but this was down for sheer familiarity with Python3 and the ease of use.
#define PY_SSIZE_T_CLEAN
#define PAM_SM_AUTH
#define PAM_SM_ACCOUNT
//#define PAM_SM_SESSION
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include </usr/include/python3.6m/Python.h>
/* expected hook */
/*
PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags, int argc, const char **argv ) {
return PAM_SUCCESS;
}
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) {
printf("Acct mgmt\n");
return PAM_SUCCESS;
}
*/
/* expected hook, this is where custom stuff happens */
PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv )
{
chdir("../code/facial"); // this changes it to the correct directory to execute
dlopen("/usr/lib/x86_64-linux-gnu/libpython3.6m.so",RTLD_LAZY | RTLD_GLOBAL);
Py_Initialize(); // Starts python interpreter
PyRun_SimpleString("import os\nimport sys\nsys.path.append(os.getcwd())"); // lets python know where we are
PyObject *mymod, *func1, *ret1;
mymod = PyImport_ImportModule("pam_detect"); // This is the .py
if (mymod != 0){ // check if the file file was loaded
func1 = PyObject_GetAttrString(mymod, "detect"); // hel is the function name in the file you declared earlier
ret1 = PyObject_CallObject(func1, NULL); // Null because the function doesnt take an argument.
if (ret1 == 1){
Py_Finalize();
return PAM_SUCCESS;
}
else{
Py_Finalize();
return PAM_AUTH_ERR;
}
}
else{
//printf("Error: can't find file!\n");
return 1;
}
Py_Finalize();
return 0;
}
You have defined the pointers but haven't assigned them to a memory address.
PyObject *mymod, *func1, *ret1;
This line in your code makes a pointer named mymod which can point to a memory containing PyObject, but you haven't given the memory address to it yet.
I don't know if calling the functions will return pointers correctly or not, So when you try to put anything there, it gives segmentation fault if you are trying to assign a variable to a pointer without a memory address.
I can only say this much without knowing where the fault occurred. try putting printf statement before assigning of all 3 pointers and see.
Program 1
In program 1 I have attempted to create the sole environment variable envar putting it in the env array which is passed to the execle function for the environments creation which program 2 will be run in.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]){
int ret;
char envar[] = "Big ol' environment variable ;D";
char *env[2] = {envar, 0};
ret = execle("./exec_test1.1", "exec_test1.1", 0, env);
printf("my prog failed ret = %d", ret);
return 0;
}
Program 2
I intended this code in the same directory to retrieve the environment variable envar on execution and to print it. However I the output in its place is null "memes and dis (null)" I have searched but can't see my mistake. Program two is almost identical to another I found for the same purpose so I assume my mistake is in program one.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char *envptr = getenv("envar");
printf("memes and dis %s\n", envptr);
return 0;
}
Thanks
You have wrong envar variable format - it must be NAME=VALUE. So fixing program 1 to:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int ret;
char envar[] = "envar=Big ol' environment variable ;D";
char *env[2] = {envar, 0};
ret = execle("./exec_test1.1", "exec_test1.1", 0, env);
printf("my prog failed ret = %d", ret);
return 0;
}
should make it work.
(I also took some liberty and formatted the code to make it more readable)
I am programming C programs in a Unix environment. I need to take a number from a user before the program is executed like so:
./program.out 60
How do I store the integer value in the C program?
You can use argv[] to get command line parameters, e.g.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
if (argc != 2) // check that we have been passed the correct
{ // number of parameters
fprintf(stderr, "Usage: command param\n");
exit(1);
}
n = atoi(argv[1]); // convert first parameter to int
// ... // do whatever you need to with `n`
return 0;
}
int main (int argc, char *argv [ ])
{
//your code
}
argv [1] will then have the address of the numeric string which contains the number.
Then you can change this to an int if needed.
It is quite simple to do and I hope I have got your question right. See below:
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("Number of arguments is: %d\n", argc);
printf("The entered value is %s\n", argv[1]);
return 0;
}
And then compile it on Linux as:
gcc file.c
./a.out 32
The program should print the value you require.
Hope this helps.
I am new in C. I want to create a file in linux C program and write environment variables in it. If file already exist I want to open and append. I have written the following code.
char *envFile=getenv("FILENAME");
int fdEnv=-1;
fdEnv=open(envFile,O_CREAT,O_RDWR,O_APPEND);
printf("%d",fdEnv);
char** env;
if(fdEnv>0)
{
for (env = environ; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s",thisEnv);
write(fdEnv,thisEnv,strlen(thisEnv));
}
close(fdEnv);
}
But when I run it first time. A blank file is created. And it stays locked after execution. Looks like some error. Second time it fdEnv stays less than 0.
I really don't understand what is happening here. Please help.
Try using | to separate the flags.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
extern char **environ;
int main(void)
{
char *envFile = getenv("FILENAME");
int fdEnv = -1;
fdEnv = open(envFile, O_CREAT|O_RDWR|O_APPEND, 0644);
printf("%d\n", fdEnv);
int i = 0;
while (environ[i]) {
printf("%s\n", environ[i]);
write(fdEnv, environ[i], strlen(environ[i]));
char lf = '\n';
write(fdEnv, &lf, 1);
i++;
}
close(fdEnv);
return 0;
}
I've run above code on my linux computer and it works.
extern char **environ;
int main()
{
char **env;
char* filename = getenv("FILENAME")
const char* mode = "a";
FILE* file = fopen( filename, mode );
for ( env = environ; *env; ++env )
fprintf( file, "%s\n", *env );
fclose(file);
return(0);
}
You should think about handling when getenv fails, is blank, etc; let me know if you have any questions.