编写程序实现以下功能:
1.输入文件名称,能够判断文件类型,判断实际用户对该文件具有哪些存取权限;
2.要求打印出文件类型信息,inode节点编号,链接数目,用户id,组id,文件大小信息;
3.修改文件的权限为当前用户读写,组内用户读写,组外用户无权限。
首先,在编写程序之前,我们需要了解如何给程序输入文件名称。利用scanf函数当然能够实现,但是在C语言中,还有一个更加方便的方法能够为程序传递所需参数。
在以前的学习中,我们可能认为main函数是没有参数的,因为main的写法是int main(),但是main函数是有且只有两个参数的。
C语言规定main函数的参数为argc和argv。其中,argc代表参数的个数,必须为int型;argv[]储存了函数的参数,必须为字符串类型的指针数组。因此,main函数的函数头可以写为:main(int argc,char *argv[])或main(int argc,char **argv)。
其中,argv[0]中储存的是程序的全名,argv[1]为第一个参数,argv[2]为第二个参数......
接下来用一个小程序来展示一下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
for(int i = 0; i < argc; i++)
{
printf("The argv[%d] is:%s\n ",i,argv[i]);
}
return 0;
}
程序运行结果:
通过这个小程序,能够很清楚的看出argc和argv[]的含义。
我们可以通过argv[]文件名传递到程序。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("Please input the filename!\n");
return 0;
}
struct stat statbuf;
int i;
for(i = 1;i < argc;i++)
{
if(lstat(argv[i],&statbuf) < 0)
perror("lstat");
char *buf;
if(S_ISREG(statbuf.st_mode))
buf = "Regular file!";
else if(S_ISDIR(statbuf.st_mode))
buf = "Directory file!";
else if(S_ISCHR(statbuf.st_mode))
buf = "Char file!";
else
buf = "Other file!";
printf("The %s is:%s\n",argv[i],buf);
printf("The %s mode is:%d\n",argv[i],statbuf.st_mode);
printf("The %s inode is:%d\n",argv[i],statbuf.st_ino);
printf("The %s uid is:%d\n",argv[i],statbuf.st_uid);
printf("The %s gid is:%d\n",argv[i],statbuf.st_gid);
printf("The %s size is:%d\n",argv[i],statbuf.st_size);
printf("The %s link num is:%d\n",argv[i],statbuf.st_nlink);
}
for(i = 1;i < argc;i++)
{
if(access(argv[i],R_OK))
printf("The user can read the %s\n",argv[1]);
else if(access(argv[i],W_OK))
printf("The user can write the %s\n",argv[1]);
else if(access(argv[i],X_OK))
printf("The user can read and write the %s\n",argv[1]);
}
for(i = 1;i < argc;i++)
{
if(chmod(argv[i],0660) < 0)
perror("chmod");
else
printf("The file.mode chmod successful!\n");
}
return 0;
}
可能有人注意到了我在修改文件权限时用到了0660这样的一串数字,那么它的含义是什么呢?
0xxxx是文件权限的另一种表示方法,一般Linux文件或目录权限分为三个,当前用户,组内用户和组外用户。每个都有三个权限rwx,即读,写,执行权限。
权限的表示方法有两种,一是直观法,即直接用rwx表示,另外一种是二进制数值法,如:644,755等。读是4,写是2,执行是1,三个相加得7,以此类推,如果是6,则表示读,写,没有执行权限。
当运行程序但并没有传入参数时,程序退出并提示输入文件名。
程序运行结果:
实验完成。