Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how to judge if the path of the file start with a given path

Tags:

c++

c

I have a path, for example, named

/my/path/test/mytestpath

, and I want to judge if it start with a given path, for example

/my/path

like image 646
zhaojing Avatar asked Oct 28 '25 16:10

zhaojing


2 Answers

The C++17 filesystem library is probably the most robust solution. If C++17 is not available to you, Boost.Filesystem provides an implementation for earlier C++ versions. Try something like:

bool isSubDir(path p, path root) 
{
    while(p != path()) {
        if(p == root) {
             return true;
        }
        p = p.parent_path();
    }
    return false;
}
like image 62
ComicSansMS Avatar answered Oct 31 '25 07:10

ComicSansMS


  1. Substring the length of the string ( /my/path ) of the original (/my/path/test/mytestpath ) from the beginning.
  2. Check whether two strings are equal.
like image 40
Mahesh Avatar answered Oct 31 '25 07:10

Mahesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!