c++ - 如何在 C++ 中重命名具有“未知”名称的文件?
问题描述
虚拟机创建一个文件,一个 .vbs 获取它的目录和名称。只需检查目录中的 .m4a 文件即可。(一次只有一个),我想重命名文件,但它说没有这样的文件或目录。
ifstream infile;
infile.open("A:\\Spotify\\Sidifyindex\\indexchecker.txt");
该文件显示“Z:\Spotify\Sidify test out\01 VVS.m4a”
getline(infile, VMin);
infile >> VMin;
infile.close();
//clear drive letter
VMin.erase(0, 1);
//add new drive letter
VMin = "A" + VMin;
//copy file dir
string outpath;
outpath = VMin;
//get new file name
outpath.erase(0, 30);
outpath = "A:\\Spotify\\Sidify test out\\" + outpath;
//convert to const char*
const char * c = VMin.c_str();
const char * d = outpath.c_str();
//rename
int result;
char oldname[] = "VMin.c_str()";
char newname[] = "outpath.c_str()";
result = rename(oldname, newname);
if (result == 0)
puts("File successfully renamed");
else
perror("Error renaming file");
cout << VMin << endl;
cout << outpath << endl;
我收到“剩余文件错误:没有这样的文件或目录”输出正确“A:\Spotify\Sidify test out\01 VVS.m4a”和“A:\Spotify\Sidify test out\VVS.m4a”
我认为问题隐藏在重命名部分的某个地方
解决方案
你写了:
char oldname[] = "VMin.c_str()";
char newname[] = "outpath.c_str()";
但你可能打算这样做:
char oldname* = VMin.c_str();
char newname* = outpath.c_str();
第一个变体将查找一个名为“VMin.c_str()”的文件,该文件不存在,因此您会收到此错误。您不小心将 C++ 代码放在引号中。引号仅用于逐字字符串,例如消息和固定文件名。但是您的文件名是通过编程确定的。
您可以使用您在上面计算的const char *
c
andd
并将这些传递给rename()
.
推荐阅读
- angular - 'ionic cordova run ios' 的构建路径有什么问题?
- mysql - 如果其他行包含带有 1 的 ID,是否可以在一列 ID 中搜索 1?
- python - 保存 CSV 文件,使其名称本身就是一个字符串
- python - Socket Server 拒绝多线程连接
- javascript - 如何检测元素可见性(z-index、固定、不透明度等)(Intersection Observer V2 替代方案)
- python-3.x - 将来自网络抓取的列表输出列表转换为数据框
- git - 已打开的新拉取请求
- amazon-web-services - Amazon AWS EC2 的实例没有互联网/错误配置?
- android - Android-GridView 中带有复选框的项目选择
- ios - 使用 NSPersistentCloudKitContainer 同步旧数据