首页 > 解决方案 > 如何在 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”

我认为问题隐藏在重命名部分的某个地方

标签: c++renamefstream

解决方案


你写了:

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 * candd并将这些传递给rename().


推荐阅读