code_junkie

strcat() new line, duplicate string

Nov 11th, 2011
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. char* prependPath( char* exeName )
  2. {
  3. char* path = getenv("PATH");
  4. char* pathDeepCopy = (char *)malloc(strlen(path) + 1);
  5. char* token[80];
  6. int j, i=0; // used to iterate through array
  7.  
  8. strcpy(pathDeepCopy, path);
  9.  
  10. //parse and split
  11.  
  12. token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0
  13. //place in array
  14. while(token[i]!= NULL) { //ensure a pointer was found
  15. i++;
  16. token[i] = strtok(NULL, ":"); //continue to tokenize the string
  17. }
  18.  
  19. for(j = 0; j <= i-1; j++) {
  20. strcat(token[j], "/");
  21. //strcat(token[j], exeName);
  22.  
  23. printf("%sn", token[j]); //print out all of the tokens
  24. }
  25. }
  26.  
  27. ...
  28. /usr/local/applic/Maple/bin/which
  29. which/which
  30. /usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which
  31. which/which
  32. Bus error (core dumped)
  33.  
  34. char* prependPath( char* exeName )
  35. {
  36. char* path = getenv("PATH");
  37. char* pathDeepCopy = strdup(path);
  38. char* token[80];
  39. int j, i; // used to iterate through array
  40.  
  41. token[0] = strtok(pathDeepCopy, ":");
  42. for(i = 0;(token[i] != NULL) && (i < 80);++i)
  43. {
  44. token[i] = strtok(NULL, ":");
  45. }
  46.  
  47. for(j = 0; j <= i; ++j)
  48. {
  49. char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1);
  50. strcpy(tmp,token[j]);
  51. strcat(tmp,"/");
  52. strcat(tmp,exeName);
  53. printf("%sn",tmp); //print out all of the tokens
  54. free(tmp);
  55. }
  56. free(pathDeepCopy);
  57. }
  58.  
  59. //parse and split
  60. token[0] = strtok(pathDeepCopy, ":");//get pointer to first token found and store in 0
  61. //place in array
  62. while(token[i]!= NULL) { //ensure a pointer was found
  63. i++;
  64. token[i] = strtok(NULL, ":"); //continue to tokenize the string
  65. }
  66.  
  67. // use new array for storing the new tokens
  68. // pardon my C lang skills. IT's been a "while" since I wrote device drivers in C.
  69. const int I = i;
  70. const int MAX_SIZE = MAX_PATH;
  71. char ** newTokens = new char [MAX_PATH][I];
  72. for (int k = 0; k < i; ++k) {
  73. sprintf(newTokens[k], "%s%c", token[j], '/');
  74. printf("%sn", newtoken[j]); //print out all of the tokens
  75. }
Add Comment
Please, Sign In to add comment