Posted By

mwb1100 on 11/05/10


Tagged

domain public prtpath


Versions (?)

prtpath.c


 / Published in: C
 

Public domain snippet that dumps a path (or other list of directories in a specified environment variable) with one directory per line.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include <string.h>
  5.  
  6. /*
  7.   get strdup() and strtok_r() from other snippets if needed
  8.  */
  9.  
  10. #ifdef _WIN32
  11. static char const* path_separators=";";
  12. #else
  13. static char const* path_separators=":";
  14. #endif
  15.  
  16.  
  17. int main( int argc, char** argv)
  18. {
  19. char* pPath;
  20. char const* envvar = "PATH";
  21.  
  22. if (argc > 1) {
  23. envvar = argv[1];
  24. }
  25.  
  26. pPath = getenv(envvar);
  27.  
  28. if (!pPath) pPath = "";
  29.  
  30. pPath = strdup( pPath);
  31.  
  32. if (!pPath) {
  33. return 1;
  34. }
  35.  
  36.  
  37. if (pPath!=NULL) {
  38. char* context = NULL;
  39. char* pDir = NULL;
  40.  
  41. for (pDir = strtok_r( pPath, path_separators, &context);
  42. pDir != NULL;
  43. pDir = strtok_r( NULL, path_separators, &context)) {
  44.  
  45. printf("%s\n", pDir);
  46. }
  47. }
  48.  
  49. free( pPath);
  50.  
  51. return 0;
  52. }

Report this snippet  

You need to login to post a comment.