C语言实现stat
mystat 用c语言实现stat
stat命令的作用
stat命令显示文件或目录的详细属性信息包括文件系统状态,比ls命令输出的信息更详细
首先学习一下stat
man stat
man -k stat | grep 2
man 2 stat
伪代码
判断是否包含文件参数
读取结构体目录文件中的信息
输出参数文件信息
关闭退出目录文件
源代码
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <string.h>
#include <time.h>
#include <sys/timeb.h>
struct stat sb;
struct tm *lt;
struct tm stm;
time_t t;
void timeswitch(struct tm *lt)
{
char nowtime[24];
memset(nowtime, 0, sizeof(nowtime));
strftime(nowtime, 24, "%Y-%m-%d %H:%M:%S", lt);
printf("%s\n", nowtime);
}
int main(int argc, char *argv[])
{
int n;
struct passwd *pwd;
// = getpwuid(sb.st_uid);
char nowtime[24];
int count[3]={0};
int cou = 0;
int flag = 0;
char mode[8]={0};
if (argc != 2)
{
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (lstat(argv[1], &sb) == -1)
{
perror("lstat");
exit(EXIT_FAILURE);
}
printf(" File: %s\n",argv[1]);
printf(" Size: %lld bytes ",(long long) sb.st_size);
printf("Block: %lld ",(long long) sb.st_blocks);
printf("IO Block: %ld ",(long) sb.st_blksize);
switch (sb.st_mode & S_IFMT)
{
case S_IFBLK: printf("Block Device\n"); break;
case S_IFCHR: printf("Character devices\n"); break;
case S_IFDIR: printf("directory\n"); flag=1; break;
case S_IFIFO: printf("FIFO/Pipeline\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("Normal files\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
printf("Device:%ld ",(long)sb.st_dev);
printf("Inode: %ld ", (long) sb.st_ino);
printf("Links: %ld\n", (long) sb.st_nlink);
printf("Access:");
printf("(");
for(n=8;n>=0;n--)
{
if(sb.st_mode&(1<<n))
{
switch(n%3)
{
case 2:
mode[8-n] = 'r';
count[n/3] += 4;
break;
case 1:
mode[8-n] = 'w';
count[n/3] += 2;
break;
case 0:
mode[8-n] = 'x';
count[n/3] += 1;
break;
default:
break;
}
}
else
{
mode[8-n] = '-';
}
}
printf("0%d%d%d/",count[2],count[1],count[0]);
if(flag)
{
printf("d");
}
else
{
printf("-");
}
for ( cou = 0; cou <= 8; cou++)
{
printf("%c",mode[cou]);
}
printf(") ");
pwd = getpwuid(sb.st_uid);
printf("UID: ( %ld/ %s) GID: ( %ld/ %s )\n",(long) sb.st_uid,pwd->pw_name, (long) sb.st_gid,pwd->pw_name);
printf("Access: ");
timeswitch(localtime(&sb.st_atime));
printf("Modify: ");
timeswitch(localtime(&sb.st_ctime));
printf("Change: ");
timeswitch(localtime(&sb.st_mtime));
printf(" Birth: -\n");
exit(EXIT_SUCCESS);
}