1

I have

char *path;

and I store the string "/home/juggler/file1.txt" in path. How do I truncate path so that I just have the parent of the last file/directory? In the example I would like to truncate path to "/home/juggler"

I was thinking of counting the number of characters(count) from the end to the last "/" and the copy the (length of path)-(count) to another string.

Thanks

Lipika Deka
  • 3,774
  • 6
  • 43
  • 56

2 Answers2

4

Try dirname(3) since you are on Linux. Being specified by SUSv3, it's quite portable.

char *dirname(char *path);

In the usual case, dirname() returns the string up to, but not including, the final '/'.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    Keep in mind that dirname alters the string, so you can't pass it string literal, (i.e. the string char *f = "/home/foo/bar" will not work, but char f[] = "/home/foo/bar"; will) – nos Aug 15 '11 at 11:48
  • @nos...Thanks, I was passing string literal to dirname and was getting segmentation fault. when i used an array of char..it worked – Lipika Deka Aug 15 '11 at 14:20
1

You should really use dirname() in libgen.h

#include <libgen.h>
#include <stdio.h>

int main()
{
    printf("%s\n", dirname("/home/juggler/file1.txt"));
    return 0;
}

Read the manpage for dirname for further info.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95