2

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();
    }
}
MahanTp
  • 744
  • 6
  • 16

3 Answers3

6

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • @BrunoParmentier Yes of course, THX for pointing that out. Next time feel free to propose an edit. – πάντα ῥεῖ May 23 '15 at 15:28
  • Be aware that the HOME environment variable can be modified by the user. The `pw_dir` entry from the `struct passwd` returned by `getpwuid( getuid() );` can't be changed by the user. – Andrew Henle May 24 '15 at 17:38
0

The second example does not work because the shell is what replaces ~ with $HOME, i.e. the path to your home directory.

fstream objects will not perform this replacement and will instead look for a directory actually called ~, which likely does not exist in your working directory.

xslr
  • 350
  • 5
  • 12
0

std::ofstream can't handle ~. It is a shortcut to your home directory. You need to give absolute path of home or the relative path with respect to the code run directory for it to work.

To give relative path, For example, if you are running your code in Desktop directory, then you needn't give ~/Desktop/Copy.cpp. Just give Copy.cpp and it should suffice.

Abhishek
  • 6,912
  • 14
  • 59
  • 85