C语言 IO函数练习

将任意文件中的数据打印到终端上

cpp 复制代码
#include <stdio.h>

int main(int argc, const char *argv[])
{
	if(argc < 2)
	{
		printf("文件名未输入,请输入文件名!\n");
		return -1;
	}
	
	//打开文件
	FILE* fo = fopen(argv[1],"r");
	if(fo == NULL)
	{
		perror("fopen");
		return -1;
	}
	
	//将任意文件中的数据打印到终端上
	char data;
	while(fread(&data, 1, sizeof(data), fo) == sizeof(data))
	{
		printf("%c", data);
	}

	//关闭文件
	fclose(fo);	
	
	return 0;
}

用read和口write实现文件拷贝

cpp 复制代码
#include <stdio.h>

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

// 用read和口write实现文件拷贝;
int main(int argc, const char *argv[])
{
	int fo = open(argv[1], O_RDONLY);
	if(fo < 0)
	{
		perror("open");
		return -1;
	}
	printf("fo = %d\n", fo);
	
	//需要拷贝的文件
	int fo2 = open(argv[2], O_WRONLY);
	if(fo2 < 0)
	{
		perror("open");
		return -1;
	}

	ssize_t res;
	char str[100];
	//循环读取文件中的数据
	while(1)
	{
		bzero(str, sizeof(str));
		res = read(fo, str, sizeof(str));
		//判断read的返回值
		if(res == 0)
		{
			printf("文件读取完毕!\n");
			break;
		}
		else if(res < 0)
		{
			perror("read");
			break;
		}
		//写入文件
		write(fo2, str, res);
	}

	//关闭文件
	if( close(fo) < 0 && close(fo2) < 0 )
	{
		perror("close");
		return -1;
	}

	return 0;
}
相关推荐
曹牧10 分钟前
BeanUtils.copyProperties‌
java
QWQ___qwq40 分钟前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
识君啊1 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
月月玩代码3 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
BUG_MeDe3 小时前
json格式字符串解析的简单使用 libjson-c
c语言·开发语言·json
阿珍爱上了阿强,在一个有星星的夜晚4 小时前
node后端页面性能监测分析
java·学习方法
Java程序之猿4 小时前
SpringBoot + camel+IBM MQ实现消息队列处理
java·spring boot·mybatis
z_鑫4 小时前
SpringCloud FeignClient 中 Bean 重复注册冲突解决方案解析
java·spring boot·spring cloud
孫治AllenSun5 小时前
【线程池】优化等待队列和拒绝策略
java·spring boot·spring cloud