系统编程中的文件链接

来源:互联网 发布:经传软件智能辅助线 编辑:程序博客网 时间:2024/06/01 12:29

系统编程中的文件链接

思维导图

这里写图片描述

示例代码

  • link函数
#include <stdio.h>#include <stdlib.h>#include <unistd.h>int main(int argc, char* argv[]){    if(argc < 3)    {        printf("a.out oldpath newpath\n");        exit(0);    }    int ret = link(argv[1], argv[2]);    if(ret == -1)    {        perror("link");        exit(1);    }    return 0;}
  • symlink函数
#include <unistd.h>#include <stdio.h>#include <stdlib.h>int main(int argc, char* argv[]){    if(argc < 3)    {        printf("a.out oldpath newpath\n");        exit(1);    }    int ret = symlink(argv[1], argv[2]);    if(ret == -1)    {        perror("symlink");        exit(1);    }    return 0;}
  • readlink函数
#include <stdio.h>#include <stdlib.h>#include <unistd.h>int main(int argc, char* argv[]){    if(argc < 2)    {        printf("a.out softlink\n");        exit(1);    }    char buf[512];    int ret = readlink(argv[1], buf, sizeof(buf));    if(ret == -1)    {        perror("readlink");        exit(1);    }    buf[ret] = 0;    printf("buf = %s\n", buf);    return 0;}
  • unlink函数

unlink函数用作处理缓存文件最为合适不过,比如视频软件(优酷app)或者下载软件(迅雷)

#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>int main(void){    int fd = open("tempfile", O_CREAT | O_RDWR, 0755);    if(fd == -1)    {        perror("open");        exit(1);    }    int ret = unlink("tempfile");    if(ret == -1)    {        perror("unlink");        exit(1);    }    char buf[512];    write(fd, "hello", 5);    lseek(fd, 0, SEEK_SET);    int len = read(fd, buf, sizeof(buf));    write(STDOUT_FILENO, buf, len);    close(fd);    return 0;}
0 0
原创粉丝点击