I want to copy a folder and all of its contents including sub-folders. I am using C on Ubuntu.
Copying regular files, and folders is easy and done so far, but the specifications for copying links (symbolic for now) is that they should link to the copied files. For now I am only interested in links inside the directory tree.
(Although links outside the tree I think should be easier - just copy the full path to the new link plus find out if they belong in the tree or not - that's hard although sarnold gave me a tip about using rsync
to achieve that)
So I have an absolute path returned by readlink:
/home/giorgos/Desktop/folder/folder1/a.pdf
Which in the worst case would be :
/home/giorgos/Desktop/folder/folder/folder/folder1/a.pdf
but I can't find a way to retrieve the relative path to my directory tree. If I could find it I could replace it with the copied directory's name:
/home/giorgos/Desktop/March/folder/myfolder/folder/folder1/a.pdf
I can't use cp or the system() function or functions of that sort, the solution has to be low level. I can use c libraries plus GNU, but please post an answer anyway I am interested.
Let us assume that you need to copy the directory SRC_DIR
to DST_DIR
, both of which are absolute paths (if not, it is trivial for you to convert them using getcwd
).
This pseudocode should cover all possibilities (it probably involves a lot of repeated use of strtok
to tokenize paths at the '/' separators):
if (SRC_DIR/SUBDIRS/LINK is a symlink that points to TARGET_LOCATION)
{
// TARGET_LOCATION may be relative *or* absolute. Make it absolute:
if (TARGET_LOCATION does not begin with '/')
{
prepend SRC_DIR/ to it
}
if (TARGET_LOCATION contains a subdirectory named '..')
{
replace occurances of 'SOMEDIRNAME/..' with ''
}
if (TARGET_LOCATION contains a subdirectory named '.')
{
replace occurances of '/.' with ''
}
// now TARGET_LOCATION is an absolute path
if (TARGET_LOCATION does not begin with SRC_DIR)
{
// symlink points outside tree
create symlink DST_DIR/SUBDIRS/LINK pointing to TARGET_LOCATION
}
else
{
// symlink points inside tree
strip SRC_DIR from beginning of TARGET_LOCATION
prepend DST_DIR to TARGET_LOCATION
create symlink DST_DIR/SUBDIRS/LINK pointing to TARGET_LOCATION
}
}
来源:https://stackoverflow.com/questions/9664944/copy-directory-with-symbolic-links-pointing-to-the-copied-files-inside-director