如何在 C++ 中重命名名称为 "unknown" 的文件?

How to rename a file with a "unknown" name in C++?

VM 创建一个文件,.vbs 获取它的目录和名称。只需检查目录中的 .m4a 文件即可。 (一次只有一个)我想重命名文件,但是它说没有这样的文件或目录。

   ifstream infile;
   infile.open("A:\Spotify\Sidifyindex\indexchecker.txt");

文件说 "Z:\Spotify\Sidify test out 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;

我正在 "Error remaining file: no such file or directory" 输出正确 "A:\Spotify\Sidify test out 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 * cd 并将它们传递给 rename()