Some guy
Some guy

Reputation: 61

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

A VM creates a file and a .vbs gets it's directory and name. Simply by checking for .m4a files in a directory. (there is only one at a time) and I'd like to rename the file, It says there is no such file or directory though.

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

The file says "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;

I'm getting "Error remaining file: no such file or directory" Output is correct "A:\Spotify\Sidify test out\01 VVS.m4a" and "A:\Spotify\Sidify test out\VVS.m4a"

I assume that the issue is hidden somewhere in the rename part

Upvotes: 1

Views: 263

Answers (1)

Johannes Overmann
Johannes Overmann

Reputation: 5161

You wrote:

char oldname[] = "VMin.c_str()";
char newname[] = "outpath.c_str()";

but you probably meant to do:

char oldname* = VMin.c_str();
char newname* = outpath.c_str();

The first variant will look for a file which is called "VMin.c_str()" which does not exist and thus you are getting this error. You accidentally have put C++ code into quotes. Quotes are only for verbatim strings, like messages and fixed filenames. But your filenames are determined programmatically.

You can use the const char * c and d you are calculating above and pass these to rename().

Upvotes: 1

Related Questions