-1

I want to delete all .txt files in the folder where the executable is located when the program closes. To delete the files I use system("del /s *.txt");, but I want to do it when the program closes so I've made a void function

void deleteTxt() {
  system("del /s *.txt");
}

and I've added the line atexit(deleteTxt()); in the main function, but compiler gives the error: "void" incompatible with "void (__cdecl *)()"

What can I do? Thanks and have a good day.

Rob
  • 14,746
  • 28
  • 47
  • 65
  • 1
    `atexit(deleteTxt());` ≠ `atexit(&deleteTxt);` – Eljay Mar 14 '21 at 16:46
  • It is `atexit(&deleteTxt);`. Note that deleting files using systems call is a bad idea (not portable and no guaranties) – Jérôme Richard Mar 14 '21 at 16:47
  • If you are using Windows specific APIs you can open the file with CreateFile with TEMPORARY and DELETE attributes and call DeleteFile on it. It will be deleted when the last handle to it closes, which would include the program exiting. However, if it is deleted no other program can open it which may or may not be OK. – Zan Lynx Mar 14 '21 at 23:38

1 Answers1

2

There are two possible solutions to this problem.

  1. Simply remove the parenthesis that calls a function and prepend an ampersand sign to denote a pointer like this:

    atexit(&deleteTxt);
    

    It is because the atexit() function accepts a type of address of a function:

    // Prototype of the atexit()
    int atexit(void (*function)(void));
    
  2. The first solution is inconvenient because of portability issues due to system calls (calling an OS-specific command). The del command is not available in Unix-like systems and only works on Windows NT systems.

    Fortunately, we have a filesystem header from the C++17 standard. So, better write your own code to delete the contents of the file safely:

    #include <filesystem>
    
    namespace fs = std::filesystem;
    
    void delete_all_files(const fs::path &name) {
    
      // Using a range-based loop to iterate till the end
      for (auto &path : fs::directory_iterator(name))
    
        // Remove each file of subdirectories iterated through the
        // directory_iterator()
        fs::remove_all(path);
    }
    
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34