How to find and remove bad or dead symbolic links using qt and c++

327 Views Asked by At

On a linux machine, I have a folder where I create many other folders dynamically inside it, and some of these folders have a symlink as well:

Example:

root@system:/run/media/data# ll
total 0
lrwxrwxrwx 1 root root 20 Aug 18 17:36 DATA1 -> /home/user/data1
lrwxrwxrwx 1 root root 24 Aug 18 17:36 DATA2 -> /home/user/data2

At some point, the target directories will get deleted but the symlinks stay.

Now I want a function to find these dead links and remove them. I tried to figure it out, but for some reason my code only finds "." and ".." folders, and can not detect "DATA1" and "DATA2".

Next problem is even if I detect "DATA1" and "DATA2" how can if figure out if they are a dead link?

QDir dir("/run/media/data");

QFileInfoList list = dir.entryInfoList();

foreach(auto& folder, list) {
    qDebug() << "Searching for dead symlinks" << folder;
    if(!folder.exists()) { // Checks tge target, if not exist, dead
        qDebug() << "REMOVING" << folder.path();
        QProcess::execute("rm", {folder.path()});
    }
}
1

There are 1 best solutions below

0
DEKKER On

thanks to Scheff's cat, I figured it that in documentation it is written for getting back the symlink the filter should be set to QDir::System