diff --git a/src/main.c b/src/main.c
index 9c59ab3d483c99aa3c8cd5aa0f75c18e64f06d77..8e3a7a383af3cc562d92524f09ca97c03d752c18 100644
--- a/src/main.c
+++ b/src/main.c
@@ -1963,11 +1963,6 @@ operate(struct Configurable *config, int argc, char *argv[])
         fprintf(config->errors, "curl: (%d) %s\n", res, errorbuffer);
 #endif
 
-      if((config->errors != stderr) &&
-         (config->errors != stdout))
-        /* it wasn't directed to stdout or stderr so close the file! */
-        fclose(config->errors);
-    
       if(config->headerfile && !headerfilep && heads.stream)
         fclose(heads.stream);
 
@@ -2012,6 +2007,11 @@ operate(struct Configurable *config, int argc, char *argv[])
   /* cleanup the curl handle! */
   curl_easy_cleanup(curl);
 
+  if((config->errors != stderr) &&
+     (config->errors != stdout))
+    /* it wasn't directed to stdout or stderr so close the file! */
+    fclose(config->errors);
+
   main_free(); /* cleanup */
 
   return res;