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;
}
相关推荐
木木子99996 分钟前
业务架构、应用架构、数据架构、技术架构
java·开发语言·架构
qq_5470261792 小时前
Flowable 工作流引擎
java·服务器·前端
鼓掌MVP3 小时前
Java框架的发展历程体现了软件工程思想的持续进化
java·spring·架构
编程爱好者熊浪4 小时前
两次连接池泄露的BUG
java·数据库
lllsure4 小时前
【Spring Cloud】Spring Cloud Config
java·spring·spring cloud
鬼火儿4 小时前
SpringBoot】Spring Boot 项目的打包配置
java·后端
NON-JUDGMENTAL4 小时前
Tomcat 新手避坑指南:环境配置 + 启动问题 + 乱码解决全流程
java·tomcat
chxii5 小时前
Maven 详解(上)
java·maven
李少兄5 小时前
IntelliJ IDEA 远程调试(Remote Debugging)教程
java·ide·intellij-idea
Kuo-Teng5 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode