当前位置: 首页 > news >正文

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

文章目录

  • 一、思维导图
  • 二、使用文件IO函数,实现文件的拷贝
    • myhead.h
    • 代码
    • 现象
  • 三、使用标准IO函数,实现图片的拷贝
    • 代码
    • 现象
  • 四、使用文件IO函数,计算文件的大小
    • 代码
    • 现象
  • 五、牛客网刷题

一、思维导图

在这里插入图片描述

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

myhead.h

#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

代码

#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函数,实现图片的拷贝

代码

#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函数,计算文件的大小

代码

#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

五、牛客网刷题

在这里插入图片描述

http://www.lryc.cn/news/607608.html

相关文章:

  • 60 GHz DreamHAT+ 雷达已被正式批准为“Powered by Raspberry Pi”产品
  • Ubuntu 24.04.2 LTS 安装mysql8.0.36保姆级教程(从安装到远程连接)
  • Elixir 协议与行为
  • 深度揭秘端口映射:原理、场景、路由映射故障,与内网IP端口映射外网工具的选择
  • LOVON——面向足式Open-Vocabulary的物体导航:LLM做任务分解、YOLO11做目标检测,最后L2MM将指令和视觉映射为动作(且解决动态模糊)
  • Go语言的gRPC教程-拦截器
  • IO流File类的基本使用
  • 【2】专业自定义图表创建及应用方法
  • JS核心语法与实战技巧
  • 力扣:2477. 到达首都的最少油耗
  • OCR、文档解析工具合集
  • EasyExcel 格式设置大全
  • LangChain详解
  • OpenShift AI - 用 Hardware profiles 为运行环境分配可用的硬件规格
  • Windows和Linux的tree工具
  • 移动端 WebView 内存泄漏与性能退化问题如何排查 实战调试方法汇总
  • 【数据结构与算法】21.合并两个有序链表(LeetCode)
  • (28)运动目标检测之随机曲线上的离散点进行插值
  • 【MySQL索引失效场景】索引失效原因及最左前缀原则详解
  • 【C语言】字符函数与字符串函数详解
  • 数据结构(11)栈和队列算法题 OVA
  • dify 升级1.7.1 插件无法下载依赖
  • [VL|RIS] ReferSAM
  • 11.Layout-Pinia优化重复请求
  • 使用 whisper, 音频分割, 初步尝试,切割为小块,效果还不错 1
  • [ Leetcode ]---快乐数
  • [lvgl_player] 用户界面(LVGL) | 播放器核心设计
  • 8.1每日一题
  • Vue 3 入门教程 8 - 路由管理 Vue Router
  • 使用GPU和NPU视频生成的优劣对比