diff --git a/src/xpdev/dirwrap.c b/src/xpdev/dirwrap.c
index 28c3c6afea5df2b2e576243be269b33f3a2026f2..e203c7636f64104edfcc793c03ccf784a1715a55 100644
--- a/src/xpdev/dirwrap.c
+++ b/src/xpdev/dirwrap.c
@@ -813,7 +813,9 @@ int delfiles(const char *inpath, const char *spec, size_t keep)
 	free(path);
 	if(keep >= g.gl_pathc)
 		return 0;
-	for(i = 0; i < g.gl_pathc && files < g.gl_pathc - keep; i++) {
+	for(i = 0; i < g.gl_pathc; i++) {
+		if(keep > 0 && files >= g.gl_pathc - keep)
+			break;
 		fpath = g.gl_pathv[i];
 		if(isdir(fpath)) {
 			fname = getfname(fpath);