7

I am a beginner in Qt, one part of my project is moving a existing file to another existing directory? Can someone gives me a specific example? I am not sure whether I should use Qfile::rename(). I try write like this

QDir::rename("/home/joshua/test.txt","/home/joshua/test/test_c.txt"); 

but the error is cannot call member function 'bool QDir::rename(const QString&, const QString&)' without object QDir::rename("/home/joshua/test.txt","/home/joshua/test/test_c.txt"); ^

Sorry guys, all are my wrong, I asked a so unclear and so stupid question, I am so sorry for wasting your time, I am a beginner, before I asked this question, I really really had not noticed that this question have been asked before, because my level is to low. Because I am too naive, I can not ask question anymore, so please, please forgive me asked this question, I am too stress because I internship at a company, my project for me is quite hard so that I have no choice to do such a wasting your time thing, lastly, I want to say thank you for those who had seen my questions before.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
innocent boy
  • 315
  • 4
  • 13
  • 2
    You can use `QFile::copy()` function first to copy a file from one directory to another, and than delete the file you have copied `QFile::remove()`. – vahancho Jul 17 '17 at 07:30
  • 2
    Before asking the question you should do a search, your question has already been answered before. To ask a good question you should read the following: https://stackoverflow.com/help/how-to-ask – eyllanesc Jul 17 '17 at 07:38

2 Answers2

9

According to the documentation:

bool QFile::rename(const QString &newName)

Renames the file currently specified by fileName() to newName. Returns true if successful; otherwise returns false.

In your case you must do the following:

QFile file("/home/joshua/test.txt");
file.rename("/home/joshua/test/test_c.txt");
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thank you. This worked. I was wondering Why QFile::copy function failed when i tried to copy a file from one drive to a different drive. – Manjunath Oct 23 '18 at 16:56
  • 1
    @Manjunath would be great to propose that question by providing a [mcve] directly asking why copy() does not work and if you rename(), I also think that should show an error message that tells us the reason. – eyllanesc Oct 23 '18 at 17:00
0

QDir::rename() is an instance method of QDir, so you need a QDir object on which to call it (and this directory will be the base for the filenames passed). For your example, something like:

QDir d("/home/joshua");
bool renamed = d.rename("test.txt" , "test/test_c.txt");

You will want to make use of the return value.

Alternatively, you could use QFile::rename() - the default directory for that is the process's current working directory.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103