• 正文
  • 相关推荐
申请入驻 产业图谱

飞凌嵌入式ElfBoard-软连接(符号链接)与硬连接之symlink和link

01/04 13:35
170
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

用于创建软链接文件。

1.头文件

#include <unistd.h>

2.函数原型

int symlink(const char *target, const char *linkpath);

3.参数

target:软链接将要指向的源文件。

linkpath:软链接的链接文件名称。

4.返回值

成功返回0,失败返回-1,并会设置errno。

2.7.2 link

用于创建硬链接文件。

1.头文件

#include <unistd.h>

2.函数原型

int link(const char *oldpath, const char *newpath);

3.参数

oldpath:硬链接的源文件。

newpath:硬链接的链接文件名称。

4.返回值

成功返回0,失败返回-1,并会设置errno。

5.示例:(使用symlink和link创建链接文件

#include <unistd.h>

#include <stdio.h>

#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

#include <stdlib.h>

int main(){

const char *source = "source.txt";

const char *soft = "soft.txt";

const char *hard = "hard.txt";

struct stat statbuf;

printf("File name:%sn",source);

if (stat(source, &statbuf) == -1) {

if (errno == ENOENT) {

fprintf(stderr,"File dies not exist:%sn",source);

} else {

perror("stat");

}

return EXIT_FAILURE;

}

if (link(source, hard) == -1) {

perror("link");

return 1;

}

printf("Hard link '%s' created successfully.n", hard);

if (symlink(source, soft) == -1) {

perror("symlink");

return 1;

}

printf("Symbolic link '%s' created successfully.n", soft);

return 0;

}

查看执行效果:

$ ./sour_soft

File name:source.txt

Hard link 'hard.txt' created successfully.

Symbolic link 'soft.txt' created successfully.

查看文件详细信息:

$ stat hard.txt soft.txt source.txt

File: hard.txt

Size: 0          Blocks: 0          IO Block: 4096   regular empty file

Device: 803h/2051d Inode: 5255791     Links: 2

Access: (0644/-rw-r--r--)  Uid: ( 1000/     elf)   Gid: ( 1000/ forlinx)

Access: 2024-09-11 15:49:06.397075102 +0800

Modify: 2024-09-11 15:49:06.397075102 +0800

Change: 2024-09-11 15:51:56.808368745 +0800

Birth: 2024-09-11 15:41:09.791123264 +0800

File: soft.txt -> source.txt

Size: 10         Blocks: 0          IO Block: 4096   symbolic link

Device: 803h/2051d Inode: 5255792     Links: 1

Access: (0777/lrwxrwxrwx)  Uid: ( 1000/     elf)   Gid: ( 1000/ forlinx)

Access: 2024-11-06 21:41:48.750334228 +0800

Modify: 2024-09-11 15:51:56.808368745 +0800

Change: 2024-09-11 15:51:56.808368745 +0800

Birth: 2024-09-11 15:51:56.808368745 +0800

File: source.txt

Size: 0          Blocks: 0          IO Block: 4096   regular empty file

Device: 803h/2051d Inode: 5255791     Links: 2

Access: (0644/-rw-r--r--)  Uid: ( 1000/     elf)   Gid: ( 1000/ forlinx)

Access: 2024-09-11 15:49:06.397075102 +0800

Modify: 2024-09-11 15:49:06.397075102 +0800

Change: 2024-09-11 15:51:56.808368745 +0800

Birth: 2024-09-11 15:41:09.791123264 +0800

从文件详细信息中可以看到soft.txt为软连接文件,hard.txt为硬连接文件。

相关推荐