开发者

Truncating a string

开发者 https://www.devze.com 2023-03-28 08:07 出处:网络
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 trun

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

精彩评论

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