Home > OS >  Problem with remove function while trying to remove a file from directory in C
Problem with remove function while trying to remove a file from directory in C

Time:07-20

I need to remove a file from a directory based on the input of user and pass it into a function that perform the file remover process

/* Class 3 veus 3:45PM*/
#include <string>
#include <iostream>
#include <stdio.h>
#include <cstdio>

void remove_file(std::string file);

int main() {
  std::string file_name;
  std::cin >> file_name;
  remove_file(file_name);
}

void remove_file(std::string file) {
     if(remove("C:\\MAIN_LOC\\"   file   ".txt") == 0) {
        std::cout << "`" << file << "`" << " Item deleted successfully" << std::endl;
    } else {
        std::cout << "[Error] File not found";
  }
}

Ok now the thing is I got several error on remove function: function "remove" cannot be called with the given argument list. I'm not sure what the error mean so I'd like for an explanation.

CodePudding user response:

remove takes a C string, but your expression "C:\\MAIN_LOC\\" file ".txt" is a C string. Use the c_str method to convert to a C string

remove(("C:\\MAIN_LOC\\"   file   ".txt").c_str())

CodePudding user response:

use the function with c string instead:

void remove_file(std::string file)
{
     std::string x = "C:\\MAIN_LOC\\"   file   ".txt";
     if(remove(x.c_str()) == 0)
     {
        ....
}
  •  Tags:  
  • c
  • Related