【发布时间】:2021-09-13 20:02:56
【问题描述】:
我想删除一个文件,该文件的名称作为程序的参数给出;但是,由于文件类型将保持不变(.bat),我希望它由程序自动给出(例如,运行deletefile.exe script 将删除“script.bat”(位于同一目录中))。我已经看到this 的问题,但该解决方案似乎不起作用。
我在这里误解了什么吗?
我的尝试如下:
#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;
}
但这会导致编译器错误
<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*
【问题讨论】:
-
@Ruzihm Ach!我应该寻找副本。啧啧。
-
@AdrianMole 我确实喜欢您在下面的回答 - 如果最终关闭,您会将其复制到另一个问题吗?我也会在那里投票
-
@Ruzihm 实际上,我不完全确定其他问题 是否 重复。不过,这肯定是密切相关的。我没有投票结束,因为那将是一个决定性(锤子)投票。