从路径获取文件夹

时间:2014-07-07 18:09:16

标签: c directory

让我们说我有一个字符串路径(就像这个):

/ROOT/DIRNAME/FILE.TXT

如何获取file.txt的父文件夹(本例中为DIRNAME)?

3 个答案:

答案 0 :(得分:1)

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

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");

答案 1 :(得分:0)

使用/找到上次出现的strrchr。复制从字符串的开头到找到的位置的所有内容。这是代码:

char str[] = "/ROOT/DIRNAME/FILE.TXT";
char * ch = strrchr ( str, '/' );
int len = ch - str + 1;
char base[80];
strncpy ( base, str, len );
printf ( "%s\n", base );

只使用字符串;不了解符号链接或其他类型的假设。

答案 2 :(得分:0)

您也可以使用指针进行操作。只需迭代到路径的末尾,然后进行备份,直到找到/,将其替换为空终止字符,然后打印字符串:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[]) {

    if (argc < 2 ) {
        fprintf (stderr, "Error: insufficient input, usage: %s path\n", argv[0]);
        return 1;
    }

    char *path = strdup (argv[1]);
    char *p = path;

    while (*p != 0) p++;

    while (--p)
        if (*p == '/') {
            *p = 0;
            break;
        }

    printf ("\n  path = %s\n\n", path);

    if (path) free (path);

    return 0;

}

输出:

$ ./bin/spath "/this/is/a/path/to/file.txt"

path = /this/is/a/path/to