C++中创建和删除软链接

假设我有一个文件 x , 下面命令创建一个软链接 y 指向 x

$ ln -s x y
$ ls -al
-rw-rw-r--.  1 louyang louyang     0 Sep 13 13:03 x
lrwxrwxrwx.  1 louyang louyang     1 Sep 13 13:03 y -> x

x如果是一个目录,命令也是一样的:

$ mkdir x
$ ln -s x y
$ ls -al
drwxrwxr-x.  2 louyang louyang     6 Sep 13 13:05 x
lrwxrwxrwx.  1 louyang louyang     1 Sep 13 13:05 y -> x

下面我们用C++程序来创建软链接:

$ cat create_soft_link.cpp 
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
    int ret = symlink("x", "y");
    if (ret == 0)
        std::cout << "create ok" << std::endl;
        std::cout << "create failed, " << strerror(errno) << std::endl;
$ g++ create_soft_link.cpp && ./a.out
create ok
$ ./a.out
create failed, File exists

删除软链接:

$ cat delete_soft_link.cpp 
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
    int ret = unlink("y");
    if (ret == 0)
        std::cout << "unlink ok" << std::endl;
        std::cout << "unlink failed, " << strerror(errno) << std::endl;
    return 0;
$ g++ delete_soft_link.cpp && ./a.out
unlink ok
$ ./a.out
unlink failed, No such file or directory

读出软链接的指向:

$ cat readlink.cpp 
#include <string>
#include <iostream>
#include <unistd.h>
#include <string.h>
int main()
    enum { BUFFERSIZE = 1024 };
    char buf[BUFFERSIZE];
    ssize_t len = readlink("y", buf, sizeof(buf)-1);
    if (len != -1)
        buf[len] = '\0';
        std::string str = buf;
        std::cout << str << std::endl;
    else {
        std::cout << "readlink failed, " << strerror(errno) << std::endl;