csubstringstrchr

Get part of string(chars) before / in C


I want to get part of a string from a user's input if "/" is provided in the input.

I used the strchr() function to check for "/". My actual problem is to be able to get the first string before / like dir/filename.txt, I want to get dir from the provided string(array of chars).

Creating a folder is not a problem as mkdir() will help me achieve it. The problem is about getting part of a string reason why I mentioned the global problem which is to use that string to create a folder.

char filename = "dir/file.txt";
if(strchr(filename, '/') !=NULL)
{
   //slash found
}

I want to strip the first part before "/" as in dir/filename.txt I want to get dir. I checked for any function to do this and could not find.

Problem solved. I was able to check the user's input and create a directory when a slash is found using

basename(user's input);

and it returns the first part before /.


Solution

  • Read up on strchr(), e.g. here
    https://en.cppreference.com/w/c/string/byte/strchr

    Check the reverse if you want the last /.
    https://en.cppreference.com/w/c/string/byte/strrchr

    If the return value is not NULL, then it points to what you were searching for, the /.

    If you use that on a non-const copy of the input string (e.g. a char array filled via https://en.cppreference.com/w/c/string/byte/strncpy ), then you can replace it by \0 to terminate the string at that point. The result is a string which ends before the first (or last) /.