如何在C ++中重命名具有“未知”名称的文件?

问题描述 投票:1回答:1

VM创建一个文件,.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测试输出\ 01 VVS.m4a”和“A:\ Spotify \ Sidify测试输出\ VVS.m4a”

我假设问题隐藏在重命名部分的某处

c++ rename fstream
1个回答
0
投票

你写了:

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()

© www.soinside.com 2019 - 2024. All rights reserved.