【问题标题】:Permissions of Current Directory当前目录的权限
【发布时间】:2014-05-30 22:43:15
【问题描述】:

我正在制作一个在 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;

}

【问题讨论】:

  • 您是否尝试过将文件名默认为"."

标签: c linux shell stat


【解决方案1】:

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

【讨论】:

  • 你的意思是像这样调用我的函数:inodeNumber(.);
  • 不,通过“。”到stat,生成你的info
  • 要么用“.”运行你的程序作为参数(使argv[1] 变为“.”),或为其添加特殊情况(可能在argc == 1 时)。
  • 好主意!工作完美!谢谢。
  • 太棒了..不要忘记检查绿色框以获取答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多