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

五、牛客网刷题

相关推荐
Slow菜鸟8 小时前
AI学习篇(三) | AI效率工具指南(2026年)
人工智能·学习
qcwl668 小时前
深入理解Linux进程与内存 学习笔记#4
笔记·学习
蒸蒸yyyyzwd9 小时前
后端学习笔记 day4
linux·笔记·学习
笨笨饿11 小时前
20_Git 仓库使用手册 - 初学者指南
c语言·开发语言·嵌入式硬件·mcu·学习
cqbelt11 小时前
Python 并发编程实战学习笔记
笔记·python·学习
智算菩萨12 小时前
【论文复现】Applied Intelligence 2025:Auto-PU正例无标签学习的自动化实现与GPT-5.4辅助编程实战
论文阅读·python·gpt·学习·自动化·复现
老神在在00112 小时前
【Selenium 自动化精讲】浏览器弹窗与登录界面的本质区别 & 实操指南
javascript·学习·selenium·测试工具·自动化
·醉挽清风·13 小时前
学习笔记—Linux—信号阻塞&信号捕捉
linux·笔记·学习
AnalogElectronic14 小时前
uniapp学习5,兼容微信小程序的俄罗斯方块游戏
学习·微信小程序·uni-app
知识分享小能手14 小时前
MongoDB入门学习教程,从入门到精通,MongoDB应用程序设计知识点梳理(9)
数据库·学习·mongodb