rename() and remove()

When using rename(oldlocation, newlocation) to move one path to another path, is it necessary to use after this the remove(oldlocation) command? In other words, does rename also delete the file in the old path or does it merely move a copy of it to the new path?
It renames the file, which means the old file is no longer there.

Rename is faster than copy/delete because it usually can just change the name of the file rather than copying it content.

Be sure to check the return value. Sometimes implementation details prohibit renaming the file, such as when the old path and the new one map to different disks.
It seems that I am having a problem in the transfer process, and not in the removal of the file on /tmp. I am trying to use rename on a text file in the /tmp directory and move it to somewhere on my home disk, /home/.../.../.../etc. Is there no way in which this can be done? I truly need it.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <fstream>
#include <cstdio>

int main()
{
    { std::ofstream( "/tmp/my_file" ) << "This is line one of the test file.\nThis is line two\nAnd this is the last line\n" ; }

    if( std::rename( "/tmp/my_file", "./my_moved_file" ) == 0 ) std::cout << "*** file was moved\n---------------\n" ;
}

http://coliru.stacked-crooked.com/a/f047b03b1fbf3e29
The problem is that rename does not seem to be able to transfer files from one disk to another. In other words, it cannot transfer from /tmp/... to /home/... . Borges, I have already tried your suggestion. Hence my other comment above.
The answer from @dhayden stated that sometimes rename doesn't work when going from 1 disk to another. In that case you will have to do a copy and remove.
@doug4: Yes, I am quite aware of this. Borges did not seem to read his post, which is what I responded to.

So, is there any easy way by which one can copy a file in c++ rather than rename it?
On a different thread, @JLBorges posted this:
1
2
3
4
5
6
7
8
#include <fstream>

void copy_file( const char* srce_file, const char* dest_file )
{
    std::ifstream srce( srce_file, std::ios::binary ) ;
    std::ofstream dest( dest_file, std::ios::binary ) ;
    dest << srce.rdbuf() ;
}
Last edited on
Thank you both for your kind assistance.
Topic archived. No new replies allowed.