c++ - Continually erasing a string leads to an infinite loop -


what trying take path in , continually erase path directory directory, checking see if symbolic link @ point. here have:

static bool islinkdirinsymlink (std::string linkpath)     {     dir *basedir;     struct dirent *currentdir;              {         basedir = opendir(linkpath.c_str());         if (basedir)             {             currentdir = readdir(basedir);             if (currentdir->d_type == dt_lnk)                 return true;             }         linkpath.erase (linkpath.find_last_of("/") + 1, linkpath.find_first_of("\0"));         } while (strcmp(linkpath.c_str(), "") != 0);      return false;     } 

this gets stuck in infinite loop. when run program in gdb happens send in linkpath of /home/user/test/linktest/out/mdirs/testdir1/test, when erases , left /home/user/test/linktest/out/mdirs/testdir1, infinite loop begins. though in same format first path when goes erase, nothing happens. have tried many different variations of erase here none seem work. have tried linkpath.append('\0') because thought maybe issue null character @ end.

thanks everyone, ended with:

char realpath[max_filelength];      {     if (realpath (linkpath.c_str(), realpath) != null)         if (strcmp(linkpath.c_str(), realpath) != 0)             return true;      size_t erasefrom = linkpath.rfind('/');     if (std::string::npos != erasefrom)         linkpath.erase(erasefrom);     } while ( !linkpath.empty() );  return false; 

because of + 1 in erase call, erasing characters 1 past / before end of string, erasing following characters:

/home/user/test/linktest/out/mdirs/testdir1/test\0                                             ^^^^ 

the first iteration of loop remove test, leaving /home/user/test/linktest/out/mdirs/testdir1/. subsequent calls erase nothing, because there 0 characters between / , \0.

you should remove + 1 linkpath.find_last_of("/") + 1 in erase call, trailing slash removed well.

moreover, erase(size_t, size_t) overload takes length of part erase second argument - find_first_of returns index of found character, not iterator it. code works accident. use std::string::npos, erase until end, instead of position of \0 character (which may not present in string if haven't called c_str() yet).


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -