当前目录的权限

时间:2014-05-30 13:33:44

标签: c linux shell stat

我正在制作一个在linux shell中执行的程序,它接受一个参数(一个文件)并显示它的inode编号,权限,文件大小等,或者如果没有给出参数,应该读取目录的权限,inode编号,大小等。

我使用stat来查找文件的这些内容,但我不确定如何在当前目录中查看此信息。

这是我的代码:

#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>

void inodeNumber(struct stat info)
{

  //printf("I-node number: %ld\n", (long)info.st_ino);
  printf("%ld ", (long) info.st_ino);

}

void filePermissions(struct stat info)
{

  //printf("File Permissions: ");
  printf((S_ISDIR(info.st_mode)) ? "d" : "-");
  printf((info.st_mode & S_IRUSR) ? "r" : "-");
  printf((info.st_mode & S_IWUSR) ? "w" : "-");
  printf((info.st_mode & S_IXUSR) ? "x" : "-");
  printf((info.st_mode & S_IRGRP) ? "r" : "-");
  printf((info.st_mode & S_IWGRP) ? "w" : "-");
  printf((info.st_mode & S_IXGRP) ? "x" : "-");
  printf((info.st_mode & S_IROTH) ? "r" : "-");
  printf((info.st_mode & S_IWOTH) ? "w" : "-");
  printf((info.st_mode & S_IXOTH) ? "x" : "-");
  //printf("\n");
  printf(" ");

}

void numberOfLinks(struct stat info)
{

  //printf("Link number: %ld\n", (long)info.st_nlink);
  printf("%ld ", (long) info.st_nlink);
  //printf(info.st_nlink);

}

void fileSize(struct stat info)
{

  //printf("File Size: %ld\n", (long)info.st_size);
  printf("%ld ", (long) info.st_size);

}

int main(int argc, char *argv[])
{

  struct stat info;
  char cwd[256];

  if (argc == 1)
  {

    //current directory
    printf("No Arguments\n");

    if (getcwd(cwd, sizeof(cwd)) == NULL )
    {

      perror("getcwd() error");
    }
    else
    {
      //find current directory
      printf("current working dir is: %s\n", cwd);

    }
    //move up directory 1 place, then test the file we were just in
    //  chdir("..");

  }

  if (stat(argv[1], &info) == -1)
  {
    perror("stat");
    exit(EXIT_FAILURE);
  }

  if (argc == 2)
  {

    inodeNumber(info);
    filePermissions(info);
    numberOfLinks(info);
    fileSize(info);
    //printf("File Name Is: %s\n", argv[1]);
    printf("%s", argv[1]);
  }

  return 0;

}

1 个答案:

答案 0 :(得分:5)

fstat()在文件和目录上的工作方式相同。对于当前目录,只需使用"."