从路径获取文件夹 [英] Getting folder from a path

查看:82
本文介绍了从路径获取文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个字符串形式的路径(像这样):

Let's say that I have a path as a string (like this one):

/ROOT/DIRNAME/FILE.TXT

如何获取file.txt的父文件夹(在这种情况下为DIRNAME)?

How can I get the parent folder of file.txt (DIRNAME in this case)?

推荐答案

对于应该至少包含一个目录的路径:

For a path that should have at least one directory in it:

char str[1024];   // arbitrary length. just for this example
char *p;
strcpy(str, "/ROOT/DIRNAME/FILE.TXT");  // just get the string from somewhere
p = strrchr(str, '/');
if (p && p != str+1)
{
    *p = 0;
    p = strrchr(p-1, '/');
    if (p) 
        print("folder : %s\n", p+1);  // print folder immediately before the last path element (DIRNAME as requested)
    else
        printf("folder : %s\n", str);  // print from beginning
}
else
    printf("not a path with at least one directory in it\n");

这篇关于从路径获取文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆