在文件名前加上前缀

Prepending to a filename

本文关键字:前缀 文件名      更新时间:2023-10-16

我正在尝试在动态创建的文件名前添加一些内容:

fstream a;
string f = argv[1];
string  fw = f.substr(0, f.rfind("."));
const char* pre = 'my_';
a.open(pre + fw.c_str(), fstream::out | fstream::in | fstream::trunc);
a.close();
a.open(pre + fw.c_str(), fstream::out | fstream::in | fstream::trunc);

但是显然我不能使用+算子来加入这个。错误:

invalid operands of types ‘const char*’ and ‘const char*’ to binary ‘operator +

对于my_语句我也得到

invalid conversion from ‘int’ to ‘const char*’

尝试以下操作。

const std::string pre="my_";
a.open((pre + fw).c_str(), fstream::out | fstream::in | fstream::trunc);

根据你的编译器和它的版本,你甚至可以使用下面的代替(不需要.c_str()部分)。

a.open(pre + fw, fstream::out | fstream::in | fstream::trunc);

既然知道了std::string,为什么还要用const char*呢?连初始化都是错误的:

const char *pre = 'my_'; // must be double-quoted

然后,如果你想连接两个const char*,而不是将指针相加,你需要使用std::strcat:

char fname[100] = "my_"; // You decide the length of the buffer, it would be MAX_PATH on Windows
a.open(std::strcat(fname, fw.c_str()), fstream::out | fstream::in | fstream::trunc);

您也可以在std::stringconst char*上使用operator+,这要简单得多:

const char *pre = "my_";
a.open(pre + fw, fstream::out | fstream::in | fstream::trunc);

但是你不应该这样做。只使用std::string:

fstream a;
string f = argv[1];
string  fw = f.substr(0, f.rfind("."));
std::string pre = "my_";
a.open(pre + fw, fstream::out | fstream::in | fstream::trunc);
a.close();
a.open(pre + fw, fstream::out | fstream::in | fstream::trunc);

修改

pre + fw.c_str()

(string(pre) + fw).c_str()

或者更好地使用c++ string:

string(pre) + fw

还请注意,您错误地定义了常量C风格字符串:

 const char *pre='my_';

应该是:

 const char *pre="my_";

string也用于pre,例如:

string pre = "my_";
//  then pre + fw