Reputation: 57
How do you move a file from one location to another using a C++ program in Linux? I've written a program to do this and it runs, but when I try to move a file to a different directory it doesn't move the file, I get the error message from the cout statement. When I try to just rename the file, moving it to the same directory with a new name it works. How can I fix my code so it will be able to move files to another directory?
Here's the code I've written:
#include <iostream>
#include <stdio.h>
using namespace std;
int main ()
{
int result=1;
char oldname[500];
char newname[500];
cout << "Enter the name of a file you want to move (include directory structure)";
cin >> oldname;
cout << "Enter the new location (include directory structure)";
cin >> newname;
result = rename( oldname , newname );
if ( result == 0 )
cout << "File successfully moved" << endl;
else
cout << "Error moving file" << endl;
return 0;
}
Edit: I added perror to my code and the error message displayed is "Error moving file: No such file or directory" even though the directory I tried moving it to does exist and it has create and delete files permissions.
Upvotes: 2
Views: 9706
Reputation: 238351
How to fix your program depends on the reason why the move (rename) failed.
The reason for the failure can be found using errno.
In this case, it was necessary to make sure that the source file exists.
For all things that need to be considered to robustly implement moving, I recommend studying an implementation of mv
command.
Upvotes: 1
Reputation: 1510
Your code will work in most cases. But you are ignoring some important things in which case it will break :
oldname
and newname
Moving between filesystems is not possible with rename()
so do it like this ( and include iostream
)
ifstream ifs(oldname, ios::in | ios::binary);
ofstream ofs(newname, ios::out | ios::binary);
ofs << ifs.rdbuf();
remove(oldname);
Before the remove()
your total disk space will be a bit less.
newname
will shrink and this is free space you have because otherwise you wouldn't able to move the file hereoldname
and newname
are on the same filesystem and you really care about this temporary loss then check whether you'll be using the same filesystem and use rename()
after all.Upvotes: 3