1. 用read函数完成文件大小计算
代码:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <IOhead.h>
int main(int argc, const char *argv[])
{
umask(07);
int fp=open("./IMG_0453.png",O_RDONLY);
if(fp<0)
{ ERR_MSG("open");
return -1;}
char buf;
ssize_t res=0;
long count=0;
while(1)
{ res=read(fp,&buf,sizeof(buf));
if(0==res)
break;
count++;
}
off_t k=lseek(fp,0,SEEK_END);
printf("%ld\n%ld\n",count,k);
close(fp);
return 0;
}
运行结果:

2. 将课上的的文件权限提取修改成循环方式
代码:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <math.h>
#include <time.h>
#include <IOhead.h>
void getmission(mode_t m)
{
putchar('-');
for(int i=9;i>=1;i--)
{ if(0 != (m & (int)pow(2,i-1)))
{
if(i%3==0)
putchar('r');
else if(i%3==2)
putchar('w');
else
putchar('x');
}
else
putchar('-');
}
return;
}
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat("./3.c",&buf)<0)
{ ERR_MSG("stat");
return -1;
}
printf("mode:%#o\n",buf.st_mode);
getmission(buf.st_mode);
return 0;
}
运行结果:

思维导图:

该代码示例展示了如何使用C语言的read函数读取文件并计算其大小,以及如何通过stat函数获取文件权限并以循环方式展示。程序首先打开并读取一个PNG文件,统计read调用的次数来估算文件大小,然后使用lseek获取精确大小。另外,它还演示了如何解析文件的权限模式并打印出rwx表示的可读、可写和可执行权限。
191

被折叠的 条评论
为什么被折叠?



