I want to remove a file, the name of which is given as an argument to the program; but, as the filetype will remain constant (.bat), I want it to be automatically given by the program (e.g. running deletefile.exe script
will delete "script.bat" (which is in the same directory)). I have seen this question, but the solution does not seem to work.
Have I misinterpreted something here?
My attempt is below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
if(argv[1] == string("del")){
string file_to_remove;
file_to_remove = argv[2]+".bat";
if (remove(file_to_remove.c_str()) != 0){
cout<<"Error in file deletion.\n";
}
else {
cout<<"Removed alias " << argv[2] << "\n";
}
}
return 0;
}
But this results in a compiler error
<source>: In function 'int main(int, char**)':
<source>:12:33: error: invalid operands of types 'char*' and 'const char [5]' to binary 'operator+'
12 | file_to_remove = argv[2]+".bat";
| ~~~~~~~^~~~~~~
| | |
| | const char [5]
| char*
The right-hand side of your file_to_remove = argv[2]+".bat";
statement is attempting to concatenate two char*
strings using the +
operator; you can't do this, and at least one of the operands must be made into a std::string
.
You can do this by constructing a temporary std:string
, like this:
file_to_remove = string(argv[2]) + ".bat";
Or, more tersely (since C++14), by adding the s
suffix to the string literal:
file_to_remove = argv[2] + ".bat"s;