开发者

Truncating a string

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 s开发者_高级运维tring.

Thanks


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 '/'.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜