Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files in a directory

Tags:

c++

qt

I need to delete all files in a directory using Qt.

All of the files in the directory will have the extension ".txt".

I don't want to delete the directory itself.

Does anyone know how I can do this? I've looked at QDir but am having no luck.

like image 488
user1794021 Avatar asked Feb 07 '13 15:02

user1794021


4 Answers

Bjorns Answer tweeked to not loop forever

QString path = "whatever";
QDir dir(path);
dir.setNameFilters(QStringList() << "*.*");
dir.setFilter(QDir::Files);
foreach(QString dirFile, dir.entryList())
{
    dir.remove(dirFile);
}
like image 190
rreeves Avatar answered Oct 24 '22 10:10

rreeves


Ignoring the txt extension filtering... Here's a way to delete everything in the folder, including non-empty sub directories:

In QT5, you can use removeRecursively() on dirs. Unfortunately, that removes the whole directory - rather than just emptying it. Here is basic a function to just clear a directory's contents.

void clearDir( const QString path )
{
    QDir dir( path );

    dir.setFilter( QDir::NoDotAndDotDot | QDir::Files );
    foreach( QString dirItem, dir.entryList() )
        dir.remove( dirItem );

    dir.setFilter( QDir::NoDotAndDotDot | QDir::Dirs );
    foreach( QString dirItem, dir.entryList() )
    {
        QDir subDir( dir.absoluteFilePath( dirItem ) );
        subDir.removeRecursively();
    }
}

Alternatively, you could use removeRecursively() on the directory you want to clear (which would remove it altogether). Then, recreate it with the same name after that... The effect would be the same, but with fewer lines of code. This more verbose function, however, provides more potential for detailed exception handling to be added if desired, e.g. detecting access violations on specific files / folders...

like image 45
user3191791 Avatar answered Oct 24 '22 10:10

user3191791


Call QDir::entryList(QDir::Files) to get a list of all the files in the directory, and then for each fileName that ends in ".txt" call QDir::remove(fileName) to delete the file.

like image 21
Jeremy Friesner Avatar answered Oct 24 '22 11:10

Jeremy Friesner


You started in a good way, look at entryList and of course pass the namefilter you want.

like image 1
Zlatomir Avatar answered Oct 24 '22 12:10

Zlatomir