LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Why are some elements missing after using strcat() (https://www.linuxquestions.org/questions/programming-9/why-are-some-elements-missing-after-using-strcat-299058/)

monil 03-08-2005 05:14 AM

Why are some elements missing after using strcat()
 
Hello,

I am trying to split the unix folder path from the file name that is entered.

For example, if the path entered is "/home/user/temp/asdf.txt"

I want to return 2 things...
Folder name: "/home/user/temp"
File Name: "asdf.txt"
Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WORD_COUNT 10

int main (int argc, char *argv[] )
{
  char text[] = "/The/quick/brown/fox/jumped/over/the/lazy/red/dog";
  char *wlist[WORD_COUNT]; /*array of 10 pointers to characters*/
  char *nwlist[WORD_COUNT];
  int i;


  printf("text[%s]\n", text);


  wlist[0] = strtok( text, "/" );
  nwlist[0] = strtok( text, "/" );


  for ( i=1; i < WORD_COUNT; i++ )
{
    wlist[i] = strtok( NULL, "/" );
}

  for ( i=0; i < WORD_COUNT-1; i++ )
{
    strcat(wlist[i], "/");
    printf("\n%s",nwlist[i]);
}

  return 0;
}

On running this, I get the following output...
Code:

text[/The/quick/brown/fox/jumped/over/the/lazy/red/dog]

The/
/
brown/
/
jumped/
/
the/
/

I have used " \n" to ensure readibility...

Kindly help me if i am wrong anywhere...

Thank you.

-Monil

Mara 03-08-2005 05:51 AM

Not a solution to your question, but why not to search the filename from the end of file? Short for loop searching the characters will be faster and probably shorter.

monil 03-08-2005 06:04 AM

Right, But, I also need the directory path too...

then, how do i remove the path and the file name?

Any idea?

-Monil

aluser 03-08-2005 07:36 AM

it's happening because strtok() modifies the string; it doesn't allocate new ones. So wlist is an array of pointers into the string text, which has its /'s turned into '\0's. When you strcat() onto each of those pointers, it writes a '\0' into the first character of the string pointed to by the next pointer. (Actually, this is only true for every other pointer, since for half of them strcat sees a 0 length first argument and overwrites a character that is not in any existing string anymore.)

That's not very clear as it's way too early in the morning. Basically you just need to realize what strtok is doing to your original string.

aluser 03-08-2005 07:40 AM

also, see dirname(3)


All times are GMT -5. The time now is 11:23 PM.