Hi,
Actually I am facing one issue while using the getenv() in the C/C++ program.
I want to take the file path from environment variables and if am not defining the environment path, its showing the message like this�!
Memory fault(coredump)
Actually I want to handle the error , when I am not defining the enviornment path.
Eg:code:
char *LOG_FILE = getenv("LOG_PATH");
FILE * pFile = fopen(LOG_FILE,"a");
int main ()
{
char name [100];
gets (name);
fprintf (pFile,"\nName %s�,name);
return 0;
}
If am getting the enviornment path locally rather than in the program mentioned above, then its working fine.But I have to use it globally.
Can anybody help me out in this?
Thanks in Advance...!
This code must be C++, since you cannot declare global variables from function return values in C. This bug is why I think that feature was a bad idea... fopen(getenv("LOG_PATH"),"a"); might work but will crash if LOG_PATH is not set, and you should be calling getenv and fopen in main instead anyway, or at least from a function which knows the proper order to set them in, which the compiler doesn't.
You can declare and initialize variables globally but it will crash if the env variable LOG_PATH is not set and make sure that the proper header files are included...
#include <stdio.h>
#include <stdlib.h>
char *LOG_FILE = getenv("LOG_PATH");
FILE *pFile = fopen(LOG_FILE, "a");
int main()
{
char name[100];
gets(name);
fprintf (pFile,"\nName %s", name);
return 0;
}
Only C++ lets you initialize global variables from function return values, and I don't think it guarantees what order they're set in -- it could call fopen before getenv gets called. C only lets you initialize them from constant values.
Yes I should have pointed out that this is only possible with a C++ compiler...C compilers don't understand global variable initializations using functions. So you can write in C but compile with a C++ compiler if that makes sense.
char *LOG_FILE = NULL;
FILE * pFile = NULL;
int main ()
{
char name [100]={0x0};
LOG_FILE=getenv("LOG_FILE");
pfile = fopen(LOG_FILE,"a");
gets (name);
if(pfile!=NULL)
fprintf (pFile,"\nName %s�,name);
return 0;
}
both pfile and LOG_FILE are now global.
Well I think jim mcnamara's solution is the best one.