-1

I'm trying to parse a string in c something like this :

/afolder/secondfolder/thirdone

do a function and that function should return this:

/afolder/secondfolder

I've tryed many things...

int getParentFolder(const char *pPathNewLink, char* TargetDirectory) {

    char *dirPath = strrchr(pPathNewLink, '/');

    strncpy(TargetDirectory, pPathNewLink, dirPath - pPathNewLink);

    return 1;
}

I cannot use operating systems libraries. I got to do it that way.

I tryed calling the function like this :

char * test;
getParentFolder("/var/lib",test);
printf("%s", test);

but I get a seg fault...

Lorac
  • 395
  • 1
  • 4
  • 14
  • Your code works for me. It do exactly what you say. Show the code which call this function, it can call it wrong. – JIghtuse Nov 21 '13 at 04:50
  • @JIghtuse I can the function like this : char* targetFolder; getParentFolder(pDirName, targetFolder); – Lorac Nov 21 '13 at 04:57
  • Have you allocate memory for TargetDirectory? – starrify Nov 21 '13 at 05:14
  • @starrify Do I have to do it inside the function or outside just declaring and char*? – Lorac Nov 21 '13 at 05:15
  • 1
    Did you null terminate `TargetDirectory`? You also didn't allocate the space for it. Both will cause problems sooner or later (not allocating sooner than not null terminating). – Jonathan Leffler Nov 21 '13 at 05:23
  • You haven't posted your working code. Here the function name defined is "getParentFolder" but you are calling "GetDirFromPath". Post your original code on which you are working. – Abhineet Nov 21 '13 at 05:24
  • @JonathanLeffler Yes this this is also what I suspect :) – starrify Nov 21 '13 at 05:27

1 Answers1

1

I suppose the reason is that you haven't allocate memory for test.
Since you're trying to strncpy to TargetDirectory, it must be initialized and have a memory region.

Try:

char *test = malloc(256);
/* or this */
char test[256];

Then do your things like:

GetDirFromPath("/var/lib",test);
printf("%s", test);

Also, if you choose the malloc one, don't forget to free it after use:

free(test);

EDITED:

Also there's another problem, sorry for didn't see it at first.
To copy the first part of the string you use strncpy, however you still need to fill the ending '\0' of the string like this:

int getParentFolder(const char *pPathNewLink, char* TargetDirectory) {
    char *dirPath = strrchr(pPathNewLink, '/');
    strncpy(TargetDirectory, pPathNewLink, dirPath - pPathNewLink);
    TargetDirectory[dirPath - pPathNewLink] = 0; // please make sure there is enough space in TargetDirectory
    return 1;
}

Please let me know if there's still any problem.

starrify
  • 14,307
  • 5
  • 33
  • 50
  • You have to use this. Or you have to define "test" as a char "test[256]". Even if now you get a SegFault, then there must be something else causing it. – Abhineet Nov 21 '13 at 05:23
  • @Lorac Yes there _is_ something else. Please see my edited answer. – starrify Nov 21 '13 at 05:26