Getting folder from a path

徘徊边缘 提交于 2019-12-12 09:27:34

问题


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

/ROOT/DIRNAME/FILE.TXT

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


回答1:


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



回答2:


Locate last occurrence of / using strrchr. Copy everything from beginning of string to the found location. Here is the code:

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

Working just with string; no knowledge of symlink or other types assumed.




回答3:


You can also do it simply using pointers. Just iterate to the end of the path and then backup until you hit a /, replace it with a null-terminating char and then print the string:

#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;

}

output:

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

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


来源:https://stackoverflow.com/questions/24616979/getting-folder-from-a-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!