Day-3 IO 练习

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;
}

结果为

文件IO函数_ck钉钉钉的博客-CSDN博客

标准IO函数&缓冲区_ck钉钉钉的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ck钉钉钉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值