文件管理(四)

编写程序实现以下功能:
1.新建文件,设置文件权限屏蔽字为0;
2.建立该文件的硬链接文件,打印硬链接文件的inode节点号和文件大小;
3.建立该文件的软链接文件,打印软链接文件的inode节点号和文件大小;打印软链接文件中的内容;
4.打印源文件的inode节点号,文件大小和链接数目;
5.调用unLink对源文件进行操作,打印源文件链接数目;

在进行程序编写之前,我们应当了解文件的软链接和硬链接的含义及两者的区别。

1.软链接,以路径的形式存在。类似于Windows操作系统中的快捷方式
2.软链接可以 跨文件系统 ,硬链接不可以
3.软链接可以对一个不存在的文件名进行链接
4.软链接可以对目录进行链接

软链接文件存放的内容是原文件的路径名。

硬链接:硬链接文件是对原文件的文件名

Linux下的每个文件都具有各自的权限位,用户要想对文件进行某种操作,就必须具有相应权限。Linux下的文件权限位如下表所示:

st_mode 含义
S_IRUSR 当前用户读(0400)
S_IWUSR 当前用户写(0200)
S_IXUSR 当前用户执行(0100)
S_IRWXU                       当前用户读、写、执行(0700)
S_IRGRP 组内用户读(0040)
S_IWGRP 组内用户写(0020)
S_IXGRP 组内用户执行(0010)
S_IRWXG 组内用户读、写、执行(0070)
S_IROTH 组外用户读(0004)
S_IWOTH 组外用户写(0002)
S_IXOTH           组外用户执行(0001)
S_IRWXO         组外用户读、写、执行(0007)

当用户创建一个文件时,需要为新的文件指定一个权限字,在实际应用中,系统有时不希望用户设置所有的权限。因此可以通过umask函数设置权限屏蔽字,直接将不需要用户干预的文件权限进行屏蔽,这样即使用户设置了相关文件权限位,系统也会将其忽略,仍然将其设为0;

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
	umask(0);
	struct stat statbuf;
	int fd = open("file",O_CREAT|O_RDWR);
	if(fd < 0)
	  perror("open");

	char *str = "hello world";
	if(write(fd,str,strlen(str)) < 0)
	  perror("write");
	
	link("./file","./hard_link");

	
	if(lstat("hard_link",&statbuf) < 0)
	  perror("lstat");

	printf("The hard_link's inode is: %d\n",statbuf.st_ino);
	printf("The hard_link's size is: %d\n",statbuf.st_size);

	symlink("file","sort_link");

	if(lstat("sort_link",&statbuf) < 0)
        perror("lstat");
 
	printf("The sort_link's inode is: %d\n",statbuf.st_ino);
        printf("The sort_link's size is: %d\n",statbuf.st_size);
	
	char buf[4];
	readlink("sort_link",buf,4);
	printf("The sort_link is: %s\n",buf);

	if(lstat("file",&statbuf) < 0)
	  perror("lstat");

	printf("The file's inode is: %d\n",statbuf.st_ino);
	printf("The file's size is: %d\n",statbuf.st_size);
	printf("The frist linknum is: %d\n",statbuf.st_nlink);

	unlink("file");

	if(lstat("file",&statbuf) < 0)
	  perror("lstat");
	printf("The second linknum is: %d\n",statbuf.st_nlink);

	close(fd);
	return 0;
}

程序运行结果:

我们可以看到,在第二次利用lstat获取file的信息时,提示没有file,这正是进行ulink的结果。

ulink函数的作用:删除目录相并减少一个连接数,如果链接数为0并且没有任何进程打开该文件,该文件内容才能被真正删除,但是若又进程打开了该文件,则文件暂时不删除直到所有打开该文件的进程都结束时文件才能被删除。

因此,运行结果中显示的第二个linknum仍然是第一个的值。

实验成功。

猜你喜欢

转载自blog.csdn.net/Wangguang_/article/details/84664557