Search code examples
c++filedirectoryfilesystems

C++ filesystem: how to remove a file that has a non-constant name


I have a function that deletes a file from the folder "settlements" by name.

My code:

void delete_settlement(string name){
     std::ostringstream oss;

     oss<<"settlements/"<<name<<".txt";
     string file_name = oss.str();
     std::ifstream file_exists;
        file_exists.open(file_name);

        //Если файл не существует, оповестить об этом пользователя
        if(!file_exists){
           cout << "File doesn't exist, it can not be deleted\n";
            std::ostringstream oss2;
            oss2<<"buffer_settlements/"<<name<<".txt";

        
        }

        else{

        std::filesystem::path tmp = std::filesystem::temp_directory_path();   
         cout << "NAME " << file_name << "\n";
         std::filesystem::path p = file_name;
         std::filesystem::remove(p);
        }

    }

I have tried using file_name instead of path instance, but this didn't work either. This code only works if the path is a constant string (i.e. I replace file_name with a constant string). What shall I do in order to implement the function?

I have tried using different ways of expressing the path to the file, but none of them worked. I always get the following runtime error: [Inferior 1 (process 9408) exited with code 03]


Solution

  • As @RichardCritten and @john pointed out, I had to close the file before deleting it.

    The solution:

    void delete_settlement(string name){
         std::ostringstream oss;
    
         oss<<"settlements/"<<name<<".txt";
         string file_name = oss.str();
         std::ifstream file_exists;
            file_exists.open(file_name);
    
            //Если файл не существует, оповестить об этом пользователя
            if(!file_exists){
               cout << "File doesn't exist, it can not be deleted\n";
                std::ostringstream oss2;
                oss2<<"buffer_settlements/"<<name<<".txt";
    
            
            }
    
            else{
                file_exists.close();
    
            std::filesystem::path tmp = std::filesystem::temp_directory_path();   
             cout << "NAME " << file_name << "\n";
             std::filesystem::path p = file_name;
             std::filesystem::remove(p);
            }
    
        }