Q:

How to move file in Linux using C++

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.

A:

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.

