1. 用read函数完成文件大小计算
#include <stdio.h>
#include <head.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <strings.h>
int main(int argc, const char *argv[])
{
umask(0);
int fd = open("666.png",O_RDONLY);
if(fd < 0)
{
ERR_MSG("open");
return -1;
}
int count = 0;
char str = '\0';
ssize_t res = 0;
while(1)
{
res = read(fd,&str,1);
if(res == 0)
break;
count++;
}
printf("size=%d\n",count);
if(close(fd) < 0)
{
ERR_MSG("close");
return -1;
}
printf("关闭成功\n");
return 0;
}
结果为
2. 将文件权限提取修改成循环方式
思路1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <head.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void get_filePermission(mode_t m)
{
int key=256,t=0; //256 = 100 000 000
int i=0;
for(i=0;i<9;i++)
{
t = (key >> i) & m ;
if(t != 0)
{
if(i % 3 == 0)
putchar('r');
else if(i % 3 == 1)
putchar('w');
else
putchar('x');
}
else
putchar('-');
}
puts("");
}
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat("write.c",&buf) < 0)
{
ERR_MSG("stat");
return -1;
}
//文件的类型和权限
printf("mode: 0%o\n",buf.st_mode);
get_filePermission(buf.st_mode);
return 0;
}
思路2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <head.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void get_filePermission(mode_t m)
{
char str[]="rwxrwxrwx"; //256 = 100 000 000
int i=0;
for(i=0;i<9;i++)
{
if(256>>i & m)
printf("%c",str[i]);
else
putchar('-');
}
puts("");
}
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat("write.c",&buf) < 0)
{
ERR_MSG("stat");
return -1;
}
//文件的类型和权限
printf("mode: 0%o\n",buf.st_mode);
get_filePermission(buf.st_mode);
return 0;
}
结果为