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;
}
相关推荐
MrSYJ5 分钟前
UserDetailService是在什么环节生效的,为什么自定义之后就能被识别
java·spring boot·后端
甄超锋35 分钟前
python sqlite3模块
jvm·数据库·python·测试工具·django·sqlite·flask
科大饭桶1 小时前
C++入门自学Day11-- String, Vector, List 复习
c语言·开发语言·数据结构·c++·容器
Felven1 小时前
C. Game of Mathletes
c语言·开发语言
long3161 小时前
构建者设计模式 Builder
java·后端·学习·设计模式
吐个泡泡v1 小时前
Maven 核心命令详解:compile、exec:java、package 与 IDE Reload 机制深度解析
java·ide·maven·mvn compile
天上掉下来个程小白1 小时前
微服务-01.导入黑马商城
java·微服务·架构
Noii.2 小时前
Spring Boot初级概念及自动配置原理
java·spring boot·后端
探索java2 小时前
Tomcat Server 组件原理
java·后端·tomcat
勿在浮沙筑高台2 小时前
无法获取实体类com.example.springdemo2.entity.po.UserPO对应的表名!
java·spring boot·mybatis