-2

I need a method to obtain the absolute path of a file in C programming language for the implementation of 'cp' UNIX's command. The objective is show an error when the source path and destination path are the same.

There are multiple possibilities, for example:

cp file .    // show error
cp ../file .
cp file file // show error

I haven't found a good method to solve this problem.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
abii
  • 11
  • 1
  • 3
  • 3
    Lookup [`realpath()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html) to get the 'real name' of a path, but it really isn't necessary. You can use [`stat()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html) to see if the device and inode number are the same for two names. Also note that if you have two files linked (`/home/user1/name1` and `/home/user2/name2`), the names might be different but still refer to the same file (and the links could be 'hard' or symbolic). – Jonathan Leffler Mar 19 '15 at 19:44
  • Thanks. It works perfectly with a few lines of code. ;) – abii Mar 19 '15 at 20:27

1 Answers1

1

Converting comments into an answer.

Lookup realpath() to get the 'real name' of a path, but it really isn't necessary. You can use stat() to see if the device and inode number are the same for two names.

Also note that if you have two files linked (for example, /home/user1/name1 and /home/user2/name2), the names might be different but still refer to the same file (and the links could be 'hard' or symbolic). You can detect their equivalence with stat() but not with realpath() — at least, not with realpath() if the link is a hard link.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278