views:

277

answers:

4

Hi all,
i have strings like "folder1/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

+3  A: 

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.

anon
You migth want to find the slash starting from the end of the string using strrchr()
Frank Bollack
Depends if he wants the first directory in the path or the whole shebang - most OS's have a function to do the latter, so I assumed the former.
anon
+3  A: 

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 */
caf
+1  A: 

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);
}
sergiom
+1  A: 

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.

Jonathan Leffler