8.1IO进程线程——文件IO函数

文章目录

一、思维导图

二、使用文件IO函数,实现文件的拷贝

myhead.h

c 复制代码
#ifndef __MYHEAD_H__
#define __MYHEAD_H__


#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define ERR_MSG(msg) do{perror(msg);printf("%d\n",__LINE__);return -1;}while(0)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#endif

代码

c 复制代码
#include <myhead.h>
int main(int argc, const char *argv[])
{
	//文件IO实现文件拷贝
	umask(0);
	//打开要下载的文件
	int fd_r=open("./myfile",O_RDONLY);
	if(fd_r==-1)
	{
		ERR_MSG("open fd_r error");
	}
	//打开要下载到的文件
	int fd_w=open("./file",O_RDWR | O_CREAT | O_TRUNC,0774);
	if(fd_w==-1)
	{
		ERR_MSG("open fd_w error");
	}
	//读取下载文件的内容
	char buf[128]="";
	if(-1==read(fd_r,buf,sizeof(buf)))
	{
		ERR_MSG("read error");
	}
	//将读取到的内容下载
	if(-1==write(fd_w,buf,strlen(buf)))
	{
		ERR_MSG("write error");
	}
	//关闭文件
	close(fd_r);
	close(fd_w);
	return 0;
}

现象

三、使用标准IO函数,实现图片的拷贝

代码

c 复制代码
#include <myhead.h>
int main(int argc, const char *argv[])
{
	FILE *fp_1=fopen("./1.png","r");
	if(fp_1==NULL)
	{
		ERR_MSG("fopen myfile_1 error");
		return -1;
	}
	char arr[4096];
	FILE *fp_2=fopen("./2.png","w");
	if(fp_2==NULL)
	{
		ERR_MSG("fopen myfile_2 error");
		return -1;
	}
	ssize_t size;
	while((size=fread(arr,1,4096,fp_1))>0)
	{
		fwrite(arr,1,4096,fp_2);
	}
	fclose(fp_1);
	fclose(fp_2);
	return 0;
}

现象



四、使用文件IO函数,计算文件的大小

代码

c 复制代码
#include <myhead.h>
int main(int argc, const char *argv[])
{
	//文件IO实现文件拷贝
	umask(0);
	//打开文件
	int fd_r=open("./myfile",O_RDONLY);
	if(fd_r==-1)
	{
		ERR_MSG("open fd_r error");
	}
	//读取文件的内容并计算长度
	char buf[128]="";
	int size;
	while(1)
	{
		ssize_t set=read(fd_r,buf,sizeof(buf));
		if(set==-1)
		{
			ERR_MSG("read error");
		}
		else if(set==0)
		{
			printf("The end of the file has been reached\n");
			break;
		}
		size+=strlen(buf);
	}
	printf("%d\n",size);

	//关闭文件
	close(fd_r);
	return 0;
}

现象

The end of the file has been reached

32

五、牛客网刷题

相关推荐
小弥儿11 小时前
GitHub今日热榜 | 2026-08-26:AI 大脑与知识管理扎堆
人工智能·学习·开源·github
荷蒲11 小时前
【小白量化Qbuddy】利用AI学习中文Python
人工智能·python·学习
中科高级技工学校11 小时前
乌鲁木齐中医康复学习经历分享
大数据·学习
JavaPub-rodert13 小时前
具身智能行业技术全景:从感知、规划、控制到 VLA 与机器人学习
学习·机器人
知识分享小能手14 小时前
概理论与数理统计学习教程,从入门到精通,在数理统计中应用R软件(22)
开发语言·学习·r语言
陈年老古董15 小时前
CentOS编译安装Python3.11完整教程
linux·笔记·学习·centos·python3.11
戈文波Geir-Wenbo Ge15 小时前
深度七步:从学习到主宰
学习
clorinda15 小时前
OpenCV实战学习记录:图像拼接与答题卡识别
人工智能·opencv·学习
red_redemption15 小时前
自由学习记录(221)
学习·renderdoc
sel_916 小时前
【OPD论文导读(二)】OPD(On-Policy Distillation)全景调研:十篇论文讲透“在自己生成的内容上学习“这件事
人工智能·python·深度学习·学习·算法·语言模型