在文件名前加上前缀
Prepending to a filename
我正在尝试在动态创建的文件名前添加一些内容:
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::string
和const 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
相关文章:
- 从命令行c++发送文本文件名
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 当Microsoft文档仅包含 C# 示例时,如何查找 C++ 包含文件名
- 编译器如何在前缀和 postix 运算符之间进行区分?
- 如何在CPP的给定目录中列出UTF编码的文件名?
- 在Visual Studio 2019中保存时ReadDirectoryChangesW文件名的问题
- 查找带有 Anaconda cmake 前缀的 boost-python3
- C++:在Windows中浏览名称中带有点的文件名
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 不带预处理器的调用方法/文件的文件名/行号
- 在 C++ 中为文件名添加时间戳
- 迭代器类的重载前缀增量运算符会引发分段错误
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 生成前缀位掩码
- 如何将文件名作为参数传入并正确打开?
- 如何在C 中读取具有前缀和时间戳为文件名的文件
- 使用regex检测带有特定前缀的DLL文件名
- 在文件名前加上前缀