Archived

This topic is now archived and is closed to further replies.

implementing pwd

This topic is 5776 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok this shouldn''t be too hard to do, heres the code i''ve written so far. I don''t have a linux machine handy to check it. Can someone have a look thru it and say if theres any obvious mistakes i''ve made?
    
#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

char *pwd(){
   size_t size = 100;
   while(1){
      char *pwdbuf = (char*) xmalloc(size);
      if(getcwd(pwdbuf,size) == pwdbuf)
          return pwdbuf;
      free(pwdbuf);
      if(errno != ERANGE)
         return 0;
      size *=2;
   }
}

int main(void){

   char *result; // *result[] maybe???


   result = pwd();
   printf("%s\n", result); // for loop in here perhaps???


   return EXIT_SUCCESS;

}    

Share this post


Link to post
Share on other sites
It all looks fine, except for the small issue that it''s hopelessly broken.

Ok, so maybe that''s an exaggeration. But your memory will never get freed when getcwd works. So whoever calls pwd will need to remember to call free on the result. Which you aren''t doing. Probably the best method is to use a static array and return a pointer to that, but then you can''t use the function in a multithreaded environment without extra work. You may as well make that buffer large, and forget about all the looping and size-doubling stuff. (There is probably a global variable telling you the maximum path length anyway - use that.)

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost ]

Share this post


Link to post
Share on other sites