Search code examples
c++file-iorelative-pathfile-copyingtilde

C++ code for copying FILES : : confused about relative address (tilde)


I've written a simple program to copy files. It gets two strings :

1) is for the path of the source file.

2) is for name of a copy file.

It works correctly when I give it the absolute or relative path(without tilde sign (~)).

But when I give it a relative path with tilde sign (~) it can't find the address of a file. And it makes me confused !

Here is my sample input :

1) /Users/mahan/Desktop/Copy.cpp

2) ~/Desktop/Copy.cpp

The first one works correctly but the second one no.

And here is my code :

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    string path, copy_name;
    cin >> path >> copy_name;
    ifstream my_file;
    ofstream copy(copy_name);
    my_file.open(path);
    if(my_file.is_open())
    {
        copy << my_file.rdbuf();
        copy.close();
        my_file.close();
    }
}

Solution

  • The ~ is handled by the shell you're using to auto expand to your $HOME directory.

    std::ofstream doesn't handle the ~ character in the filepath, thus only your first sample works.


    If you pass the filepath to your program from the command line using argv[1], and call it from your shell, you'll get the ~ automatically expanded.


    With what was said above, if you want to expand the ~ character yourself, you can use the std::getenv() function to determine the value of $HOME, and replace it with that value.