Archived

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

pdstatha

Implementing pwd

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;

}    
Edited by - pdstatha on February 18, 2002 4:58:02 PM

Share this post


Link to post
Share on other sites
I had to change it (not much) to get it to compile. After compiling correctly it worked though.
  
#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <sys/types.h>


char *pwd(void) {
size_t size = 100;

while(1) {
char *pwdbuf = (char *) malloc(size);

if(getcwd(pwdbuf,size) == pwdbuf)
return pwdbuf;

free(pwdbuf);

if(errno != ERANGE) return 0;

size *= 2;
}
}

int main(void) {
char *result;

result = pwd();
printf("%s\n", result);
free(result);

return EXIT_SUCCESS;
}


Share this post


Link to post
Share on other sites
Thanks m8 that was helpful, now for something which should be even easier, implementing cd. If you could do the same for the following I will be forever in your debt.

  
#include <errno.h>

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <stdlib.h>

//takes the directory as command line arg

main(int argc, char **argv) {

if(argv[1] != ''\0'') {
if((errno = chdir(argv[1])) == ENOTDIR)
printf("Can''t change to %s\n", argv[1]);
}else
printf("Usage:%s dir_name\n", argv[0]);

return (0);

}






Share this post


Link to post
Share on other sites
It works, but I changed it to be a little better. I made it ANSI-compliant, added a return error so that if your program was the actual "cd" then shell scripts could detect if an error occured, and some little stupid things that I just felt like.
        
#include <errno.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>


int main(int argc, char **argv) {
if(argc > 1 && argv[1] != NULL) {
if((errno = chdir(argv[1])) == ENOTDIR) {
printf("Can't change to %s\n",argv[1]);
return -1;
}
} else printf("Usage: %s dir_name\n", argv[0]);

return 0;
}

Edit: Fixed extreme code mangling.


Edited by - Null and Void on February 18, 2002 6:16:32 PM

Share this post


Link to post
Share on other sites