Ad

Substring C From String Like Folder1/file1.txt

- 1 answer

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

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad