一、用read函数完成文件大小计算
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int fd = open("./1.txt",O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open success!\n");
off_t size = lseek(fd,0,SEEK_END);
printf("size=%ld\n",size);
char c;
ssize_t res = 0;
int count = 0;
lseek(fd,0,SEEK_SET);
while(1)
{
res = read(fd,&c,1);
if(0 == res)
break;
count++;
}
printf("count=%d\n",count);
if(close(fd) < 0)
{
perror("close");
return -1;
}
printf("close success!\n");
return 0;
}
二、将文件权限提取修改成循环方式
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
void get_filePermission(mode_t m)
{
long x = 0400;
char c[]="rwx";
int count = 0;
while(x)
{
if((m & x) == 0)
putchar('-');
else
printf("%c",c[count%3]);
count++;
x = x >> 1;
}
putchar(' ');
}
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat("./1.txt",&buf) < 0)
{
perror("stat");
return -1;
}
printf("0%o ",buf.st_mode);
get_filePermission(buf.st_mode);
printf("%ld ",buf.st_nlink);
printf("%d ",buf.st_uid);
printf("%d ",buf.st_gid);
printf("%ld ",buf.st_size);
struct tm *info=NULL;
info = localtime(&buf.st_mtime);
// printf("%ld ",buf.st_ctime);
printf("%d-%02d-%02d %02d:%02d:%02d\n",info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
return 0;
}