[SOLVED] How to rename a directory?



  • Hello,

    I'm trying to change the name of a directory and I'm unsure how to do this.
    I've found the QDir::rename function, however it requires an old name? This is really odd, since when you're using the function you've already created an object with the directory in it, so why would it need the old name?
    What I'm trying to achieve is:
    @QDir currentDirectory("C:\SomeDirectory\A");
    currentDirectory.rename("B");
    // Now the directory should be renamed to C:\SomeDirectory\B@

    Could someone provide an example on how to do this?

    Thanks!



  • [quote author="Qub1" date="1411849364"]
    @QDir currentDirectory("C:\SomeDirectory\A");
    currentDirectory.rename("B");
    // Now the directory should be renamed to C:\SomeDirectory\B@
    [/quote]

    This specification for C:\SomeDirectory\A won't work. The compiler will attempt to handle \S and \A as escape sequences, and likely fail. If the compiler being used supports C++ 0x11, raw strings can be used, or \ can be escaped as \.
    @
    // C++ 0x11 raw string
    QDir currentDirectory(R"(C:\SomeDirectory\A)");
    // C string with \ escaped
    QDir currentDirectory("C:\SomeDirectory\A");
    @

    Either way, Qt uses "/" for the directory separator. Use QDir::fromNativeSeparators() and toNativeSeparators() if file paths will be coming in or going out in the native form.

    One solution to the rename problem that spawned the thread is:
    @ QDir currentDirectory(...)
    currentDirectory.rename(currentDirectory.path(), "../B")@



  • Ah, thanks for that! It is working now. And regarding the escape character, sorry, I was just writing an example from on the fly :) - didn't think about that



  • Alright, so I did some more testing and it appears that just creates a new folder with the new name, but none of the files are inside and the old folder with the old name is still there. So all it does is create a new empty folder.

    EDIT: Nevermind, I was doing it wrong :S


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.