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;
}
相关推荐
木头没有瓜1 小时前
idea离线安装插件
java·ide·intellij-idea
llwszx1 小时前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
述雾学java1 小时前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel
保持学习ing1 小时前
苍穹外卖day3--公共字段填充+新增菜品
java·阿里云·实战·springboot·前后端·外卖项目·阿里云文件存储
呜喵王阿尔萨斯1 小时前
编程中的英语
c语言·c++
77qqqiqi2 小时前
正则表达式
java·后端·正则表达式
厦门德仔2 小时前
【WPF】WPF(样式)
android·java·wpf
大春儿的试验田2 小时前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
Gappsong8742 小时前
【Linux学习】Linux安装并配置Redis
java·linux·运维·网络安全
hqxstudying2 小时前
Redis为什么是单线程
java·redis