2.28文件IO fread、read-write

1.用fread实现,将任意文件中的数据显示到终端上。

#include <stdio.h>



int main(int argc, const char *argv[])
{
	if(argc < 2)
	{
		printf("请传参\n");
		return -1;
	}
	
	FILE* fp = fopen(argv[1],"r");
	

	char c;
	int re=0;
	
	while( fread(&c,1,sizeof(c),fp) > 0 )
	{
		printf("%c",c);
	}
	putchar(10);
	fclose(fp);
	
	return 0;
}

2.用read和write实现文件拷贝。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main(int argc, const char *argv[])
{
	int op = open("./test.txt",O_RDONLY,0775);
	if(op < 0)
	{
		perror("op");
		return -1;
	}
	printf("op=%d\n",op);
	int op_w = open("./copy_readwrite.txt",O_WRONLY|O_CREAT|O_TRUNC,0775);
    if(op < 0)
    {
        perror("op");
        return -1;    
    }
	printf("op_w=%d\n",op_w);

	// ssize_t t=0;
	char c;
	while( read(op,&c,sizeof(c)) > 0 )
	{
		write(op_w,&c,sizeof(c));
	}
	
	int reop,reop_w;
	reop = close(op);
	if(reop < 0)
	{
		perror("reop");
		return -1;
	}
	close(op_w);
	if(reop_w < 0)
	{
		perror("reop_w");
		return -1;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值