简体   繁体   中英

Relocating and renaming file C++ using stdio.h

I am trying to rename a file with the rename() function of stdio.h and it works but the problem is that it can only rename files located in the folder of the current project, I would like to be able to select a directory and if it is possible to change it from location in the process.

#include "stdafx.h"
#include <iostream>
#include <stdio.h>

int main()
{
    bool verifier;
    char oldName[] = "text.txt";
    char newName[] = "newText.txt";
    verifier = rename(oldName, newName);

    if (!verifier)
    {
        std::cout << "The file has been succesfully renamed\n";
    }
    else
    {
        std::cout << "There was a problem renaming the file\n";
    }

    return 0;
}

Thank you!

By default, the root directory path is the location which the executable is running in. If you want to access another folder above our outside that location, you can use an absolute path (ie C:/path/to/old.txt).

#include "stdafx.h"
#include <iostream>
#include <stdio.h>

int main()
{
   char oldName[] = "C:\\path\\to\\your\\proj\\text.txt"; // char oldName[] = "old.txt";
   char newName[] = "C:\\test\\output\\folder\\new.txt"; // char newName[] = "newText.txt";
   bool verifier = rename(oldName, newName);

   if (!verifier)
   {
      std::cout << "The file has been succesfully renamed\n";
   }
   else
   {
      std::cout << "There was a problem renaming the file\n";
   }
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM