5

I am trying to copy a file from one location to another( in a device) using C++/Qt

I tried QFile::copy("path1/file","path2");

I want to copy the file in path1 to path2. path2 does not have the file.

I just want to know if this is the right way because the above code does not seem to work.

Also, should I do a file open before I try to copy? Need help!

user1065969
  • 589
  • 4
  • 10
  • 19
  • Also, have you verified in the docs that your plan for using this function is supported? http://doc.trolltech.com/4.7/qfile.html#copy – San Jacinto May 11 '12 at 18:32

1 Answers1

13

If you want to copy path1/file into path2 with the same file name, you'll want to do:

QFile::copy("path1/file", "path2/file");

Copy allows you to change the name of the file. Example:

QFile::copy("path1/file1", "path1/file2");

Which is why you need to include the file name both times. Also, it is not necessary to open the file first. And to answer the title question, it copies the file. QFile::rename() moves the contents.

Joel Rondeau
  • 7,486
  • 2
  • 42
  • 54
  • Thank you! I have one more question. This Qfile copy would return false in case file already exists in the destination location. I want to copy the file first time and every time the contents of source file is modified. In the second case I have to go for QFile rename()? – user1065969 May 14 '12 at 14:33
  • 1
    No. Both copy and rename will fail if the file already exists. You have to delete the destination file first. – Joel Rondeau May 15 '12 at 02:06
  • 2
    Can this be used to copy a **resource file** to some path? For example, is `QFile::copy(":/default.jpg", "data.jpg");` possible? – Shravan Jun 11 '15 at 17:51
  • 1
    @ThePeacefulCoder You should ask that as a new question. Unfortunately, I don't know the answer to that. – Joel Rondeau Jun 11 '15 at 17:53
  • 1
    @ThePeacefulCoder This link claims that it does work for copying a resource file: https://forum.qt.io/topic/13131/how-to-extract-a-resource-from-qrc-solved/2 – Joel Rondeau Jun 11 '15 at 17:57
  • @JoelRondeau Thanks! :) – Shravan Jun 11 '15 at 17:58