开发者

Substring C from string like folder1/file1.txt

开发者 https://www.devze.com 2022-12-18 06:27 出处:网络
i have strings like \"fo开发者_JAVA百科lder1/file1.txt\" or \"foldername1/hello.txt\" and i need to take the substring that identify the folder name with the slash (/) included (example: from \"folder

i have strings like "fo开发者_JAVA百科lder1/file1.txt" or "foldername1/hello.txt" and i need to take the substring that identify the folder name with the slash (/) included

(example: from "folder1/file1.txt" i need "folder1/").

The folders name are not all with the same length. How can i do this in C?? thanks


First, find the position of the slash with strchr:

char * f = "folder/foo.txt";  // or whatever
char * pos = strchr( f, '/' );

then copy into a suitable place:

char path[1000];   // or whatever
strncpy( path, f, (pos - f) + 1 );
path[(pos-f)+1] = 0;    // null terminate

You should really write a function to do this, and you need to decide what to do if strchr() returns NULL, indicating the slash is not there.


Find the last '/' character, advance one character then truncate the string. Assuming that the string is modifiable, and is pointed to by char *filename;:

char *p;

p = strrchr(filename, '/');
if (p)
{
    p[1] = '\0';
}

/* filename now points to just the path */


You could use the strstr() function:

char *s = "folder1/file1.txt";
char folder[100];

char *p = strstr(s, "/");
if (0 != p)
{
    int len = p - s + 1;
    strncpy(folder, s, len);
    folder[len] = '\0';
    puts(folder);
}


If you work on a POSIX machine, you can look up the dirname() function, which does more or less what you want. There are some special cases that it deals with that naïve code does not - but beware the weasel words in the standard too (about modifying the input string and maybe returning a pointer to the input string or maybe a pointer to static memory that can be modified later).

It (dirname()) does not keep the trailing slash that you say you require. However, that is seldom a practical problem; adding a slash between a directory name and the file is not hard.

0

精彩评论

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