This is probably something simple, but I can’t figure out why I can’t get the value from this char*.
Here is my issue:
static char* DIR_ENTRY_PATH = NULL;
…
while (1) // infinite loop
{
// accept a client connection
clientFd = accept (serverFd, clientSockAddrPtr, &clientLen);
if (fork() == 0) // Create child proc to get dir entry info
{
//read dir entry info
readInfo(clientFd);
printf("dpath: %s\n", DIR_ENTRY_PATH); //prints out the the correct value (DIR_ENTRY_PATH set in readInfo)
int test = 1;
//get dir entry info and write back
DIR *dir;
struct dirent *entry; //pointer to dir entry
struct stat stbuf; //contains file info
if((dir = opendir(DIR_ENTRY_PATH)) == NULL){ //make sure entry is valid
printf("error with dirent\n");
exit(1);
}
else{
printf("gathering directory entry info...\n");
while((entry = readdir(dir)) != NULL){
char *entryname = entry->d_name;
printf("path: %s\n", DIR_ENTRY_PATH); /*prints nothing out.. */ - PROBLEM IS HERE
printf("int: %d\n", test); //*prints 1 out.. */
…
readInfo():
//reads info from the client
void readInfo(int fdesc){
int fd = fdesc;
char str[200];
readLine(fd, str); //read line in from socket
DIR_ENTRY_PATH = str;
printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}
//reads a single line
int readLine(int fdesc, char *strng){
int fd = fdesc;
char *str = strng;
int n;
do{
n = read(fd,str, 1); //read a single character
}while(n > 0 && *str++ != 0);
return (n>0); //return false if eoi
}//end readLine
Why am I able to get the value of the test int but not the dir_entry_path? Thanks for any help.
You are assigning a pointer to a local variable to your global variable, but once the function returns, the local variable is gone!
After the function returns, the local variable is undefined, and its storage can be reused by the next function, etc.
How to fix the problem? There are many possible ways, but the simplest might be:
As a stylistic point, ALL_CAPS normally denotes a macro, or an
enumvalue (becauseenumis a bit like#definewhich uses ALL_CAPS).I hope you have proper bounds checking on
readLine(). I got lazy with my modification and simply ensured the global was (five times) longer than the local variable. Tune to suit yourself. I’d also use anenumfor the buffer size (and a lower-case name instead ofDIR_ENTRY_PATH).