实验四
编写程序实现以下功能:
1.新建文件,设置文件权限屏蔽字为0;
2.建立该文件的硬链接文件,打印硬链接文件的inode节点号和文件大小;
3.建立该文件的软链接文件,打印软链接文件的inode节点号和文件大小;打印软链接文件中的内容;
4.打印源文件的inode节点号,文件大小和链接数目;
5.调用unlink对源文件进行操作,打印源文件链接数目;
代码如下:
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
int main(int argc,char* argv[])
{
int fd,fds,fdx,wd;
struct stat statBuf,statBufs,statBufx;
fd=open("f3",O_RDWR|O_CREAT);
if(fd<0)
{
perror("open f3");
exit(-1);
}
fchmod(fd,S_IRWXU|S_IRWXG|S_IRWXO);
char *str="abcdefg";
wd=write(fd,str,strlen(str));
if(wd!=strlen(str))
perror("write fd");
else
printf("\nwrite ok\n");
umask(0);
int li=link("f3","f3_s");
if(li<0)
{
perror("link");
exit(-1);
}
stat("f3_s",&statBufs);
printf("hard link file inode:%ld\n:",statBufs.st_ino);
printf("hard link file size:%d\n",statBufs.st_size);
stat("f3",&statBufx);
int sli=symlink("f3","f3_x");
if(sli<0)
{
perror("symlink");
exit(-1);
}
lstat("f3_x",&statBufx);
//printf("symbolic link file inode:",statBufx.st_ino);
//printf("symbolic link file size:",statBufx.st_size);
char strs[1024];
int rdx=readlink("f3_x",strs,1024);
if(rdx<0)
{
perror("read fd");
exit(-1);
}
else
printf("read ok\n");
printf("symbolic link file inode:%ld\n",statBufx.st_ino);
printf("symbolic link file size:%ld\n",statBufx.st_size);
printf("symbolic link file content:%s\n",strs);
fstat(fd,&statBuf);
printf("file inode:%ld\n",statBuf.st_ino);
printf("file size:%d\n",statBuf.st_size);
printf("file link number:%ld\n",statBuf.st_nlink);
if(unlink("f3")<0)
{
perror("unlink");
exit(-1);
}
printf("after unlink,file link number:%ld\n",statBuf.st_nlink);
close(fd);
return 0;
}