c實現cat命令

墨塵深巷發表於2018-07-19
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <sys/types.h>
#include <grp.h>
#include <sys/stat.h>
 
int cats(const char *filename);
void print(const char *filename, struct stat *st);
void mode_to_letters(int mode, char * str);
char *uid_to_name(uid_t uid);
char *gid_to_name(gid_t gid);
void Usage();
 
int main(int argc, char **argv)
{
  if (argc < 2)
  {
    Usage();
    return -1;
  }
  else
  {  
    cats(argv[1]);
  }
  return 0;
}
 
int cats(const char *filename)
{
  FILE *fp = NULL;
  char *buffer = NULL;
  struct stat st;
  stat(filename, &st);
  int number = 0;
  buffer = (char *)malloc(sizeof(char)*st.st_size);
  memset(buffer, 0, st.st_size);
 
  fp = fopen(filename, "r");
  if (fp == NULL)
  {
    printf("open file failer!\n");
    fclose(fp);
    return -1;
  }
 
  number = fread(buffer, st.st_size, 1, fp);
  if (number < 0)
  {
    printf("read file failer!\n");
    fclose(fp);
    return -1;
  }
 
  print(filename, &st);
  printf("%s", buffer);
 
  free(buffer);
  buffer = NULL;
 
  fclose(fp);
  return 0;
}
 
void print(const char *filename, struct stat *st)
{
  char modestr[11];
 
  mode_to_letters( st->st_mode, modestr );
 
  printf("\n*********************************************\n");
  printf("File  Name:\t%s\n",filename);
  printf("File EePer:\t%s\n", modestr);
  printf("File  Size:\t%ld bytes\n", (long)st->st_size);
  printf("ID  Users:\t%s\n", uid_to_name(st->st_uid));
  printf("ID   Group:\t%s\n", gid_to_name(st->st_gid));
  printf("Last MTime:\t%s", (char *)(4+ctime(&st->st_mtime)));
  printf("*********************************************\n\n");
}
 
void mode_to_letters(int mode, char *str)
{
  strcpy(str, "----------");     
 
  if (S_ISDIR(mode))  
  {
    str[0] = 'd'; 
  }  
 
  if (S_ISCHR(mode))  
  {
    str[0] = 'c'; 
  }   
 
  if (S_ISBLK(mode))  
  {
    str[0] = 'b';
  }    
 
  if (mode & S_IRUSR) 
  {  
    str[1] = 'r';    
  }
  if (mode & S_IWUSR) 
  {
    str[2] = 'w';
  }
  if (mode & S_IXUSR) 
  {
    str[3] = 'x';
  }
 
  if (mode & S_IRGRP) 
  {
    str[4] = 'r';   
  }
  if (mode & S_IWGRP) 
  {
    str[5] = 'w';
  }
  if (mode & S_IXGRP)
  {
    str[6] = 'x';
  }
 
  if (mode & S_IROTH)
  {
    str[7] = 'r';  
  } 
  if (mode & S_IWOTH) 
  {
    str[8] = 'w';
  }
  if (mode & S_IXOTH) 
  {
    str[9] = 'x';
  }
}
 
char *uid_to_name(uid_t uid)
{
  struct  passwd *pw_ptr;
  static  char numstr[10];
 
  if ((pw_ptr = getpwuid(uid)) == NULL)
  {
    sprintf(numstr, "%d", uid);
    return numstr;
  }
  else
  {
    return pw_ptr->pw_name ;
  }
}
 
char *gid_to_name(gid_t gid)
{
  struct group *grp_ptr;
  static  char numstr[10];
 
  if ((grp_ptr = getgrgid(gid)) == NULL)
  {
    sprintf(numstr, "%d", gid);
    return numstr;
  }
  else
  {
    return grp_ptr->gr_name;
  }
}
 
void Usage()
{
  printf("format error!Parameter input format:\n");
  printf("\tformat: ./cats filename\n");
}

 

相關文章