Linux 文件:IO接口详解及实操

news2024/9/28 17:22:43

一、C语言中的文件IO读写操作

在c语言文件中,创建、打开、读、写操作可以通过如下的代码进行:

1.1写文件

通过'w'指令对文件进行写入操作时,编译器会先将文件内容清空然后重新写入。

#include <stdio.h>
#include <string.h>
int main()
{
     FILE *fp = fopen("myfile", "w");
     if(!fp){
     printf("fopen error!\n");
     }
     const char *msg = "hello bit!\n";
     int count = 5;
     while(count--){
     fwrite(msg, strlen(msg), 1, fp);
     }
     fclose(fp);
     return 0;
}

1.2读文件

#include <stdio.h>
#include <string.h>
int main()
{
 FILE *fp = fopen("myfile", "r");
 if(!fp){
 printf("fopen error!\n");
 }
 char buf[1024];
 const char *msg = "hello linux!\n";
while(1){
 //注意返回值和参数,此处有坑,仔细查看man手册关于该函数的说明
 ssize_t s = fread(buf, 1, strlen(msg), fp);
 if(s > 0){
 buf[s] = 0;
 printf("%s", buf);
 }
 if(feof(fp)){
 break;
 }
 }
 fclose(fp);
 return 0;
}

1.3输出文件

#include <stdio.h>
#include <string.h>
int main()
{
 const char *msg = "hello fwrite\n";
 fwrite(msg, strlen(msg), 1, stdout);
 printf("hello printf\n");
 fprintf(stdout, "hello fprintf\n");
 return 0;
}

1.4stdin & stdout & stderr

C默认会打开三个输入输出流,分别是stdin, stdout, stderr。
仔细观察发现,这三个流的类型都是FILE*, fopen返回值类型,文件指针。
 r Open text file for reading. 
 The stream is positioned at the beginning of the file.
 
 r+ Open for reading and writing.
 The stream is positioned at the beginning of the file.
 
 w Truncate(缩短) file to zero length or create text file for writing.
 The stream is positioned at the beginning of the file.
 
 w+ Open for reading and writing.
 The file is created if it does not exist, otherwise it is truncated.
 The stream is positioned at the beginning of the file.

a Open for appending (writing at end of file). 
 The file is created if it does not exist. 
 The stream is positioned at the end of the file

a+ Open for reading and appending (writing at end of file).
 The file is created if it does not exist. The initial file position
 for reading is at the beginning of the file, 
 but output is always appended to the end of the file

二、系统文件IO

操作文件,除了上述 C 接口(当然, C++ 也有接口,其他语言也有),我们还可以采用系统接口来进行文件访问,先来直接以代码的形式,实现和上面一模一样的代码:

2.1写文件

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
 umask(0);
 int fd = open("myfile", O_WRONLY|O_CREAT, 0644);
 if(fd < 0){
 perror("open");
 return 1;
 }
 int count = 5;
 const char *msg = "hello linux!\n";
 int len = strlen(msg);
 while(count--){
 write(fd, msg, len);//fd:系统返回的文件描述符 , msg:缓冲区首地址, len: 本次读取,期望写入多少个字节的数
据。 返回值:实际写了多少字节数据
 }
 close(fd);
 return 0;
}

2.2读文件

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
 int fd = open("myfile", O_RDONLY);
 if(fd < 0){
 perror("open");
 return 1;
 }
 const char *msg = "hello linux!\n";
 char buf[1024];
 while(1){
 ssize_t s = read(fd, buf, strlen(msg));//类比write
 if(s > 0){
 printf("%s", buf);
 }else{
 break;
 }
 }
 close(fd);
 return 0;
}

2.3接口功能介绍

open:
open 函数具体使用哪个,和具体应用场景相关,如目标文件不存在,需要open创建,则第三个参数表示创建文件的默认权限,否则,使用两个参数的open。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
pathname: 要打开或创建的目标文件
flags: 打开文件时,可以传入多个参数选项,用下面的一个或者多个常量进行“或”运算,构成flags。
参数:
 O_RDONLY: 只读打开
 O_WRONLY: 只写打开
 O_RDWR : 读,写打开
 这三个常量,必须指定一个且只能指定一个
 O_CREAT : 若文件不存在,则创建它。需要使用mode选项,来指明新文件的访问权限
 O_APPEND: 追加写
返回值:
 成功:新打开的文件描述符
 失败:-1
系统调用接口和库函数的关系,一目了然。
所以,可以认为, f# 系列的函数,都是对系统调用的封装,方便二次开发。

2.4文件描述符fd

Linux进程默认情况下会有3个缺省打开的文件描述符,分别是标准输入0, 标准输出1, 标准错误2.
0,1,2对应的物理设备一般是:键盘,显示器,显示器
所以输入输出还可以采用如下方式
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
 char buf[1024];
 ssize_t s = read(0, buf, sizeof(buf));
 if(s > 0){
 buf[s] = 0;
 write(1, buf, strlen(buf));
 write(2, buf, strlen(buf));
 }
 return 0;
}

而现在知道,文件描述符就是从 0 开始的小整数。当我们打开文件时,操作系统在内存中要创建相应的数据结构来描述目标文件。于是就有了file 结构体。表示一个已经打开的文件对象。而进程执行 open 系统调用,所以必须让进程和文件关联起来。每个进程都有一个指针*files, 指向一张表 files_struct, 该表最重要的部分就是包涵一个指针数组,每个元素都是一个指向打开文件的指针!所以,本质上,文件描述符就是该数组的下标。所以,只要拿着文件描述符,就可以找到对应的文件。

三、文件描述符分配规则

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
 int fd = open("myfile", O_RDONLY);
 if(fd < 0){
 perror("open");
 return 1;
 }
 printf("fd: %d\n", fd);
 close(fd);
 return 0;
}//结果为fd:3
int main()
{
 close(0);
 //close(2);
 int fd = open("myfile", O_RDONLY);
 if(fd < 0){
 perror("open");
 return 1;
 }
 printf("fd: %d\n", fd);
 close(fd);
 return 0;
}//结果为0
文件描述符的分配规则:在 files_struct 数组当中,找到当前没有被使用的最小的一个下标,作为新的文件描述符。

四、重定向

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
 close(1);
 int fd = open("myfile", O_WRONLY|O_CREAT, 00644);
 if(fd < 0){
 perror("open");
 return 1;
 }
 printf("fd: %d\n", fd);
 fflush(stdout);
 
 close(fd);
 exit(0);
}
此时,我们发现,本来应该输出到显示器上的内容,输出到了文件 myfile 当中,其中, fd 1 。这种现象叫做输出重定向。当编译器去进行printf时会默认去打开fd=1的文件描述符所指向的,此时我们将myfile文件放到这个位置,那么编译器就会往myfile文件中进行写入。

五、使用dup2系统调用

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
 int fd = open("log.txt", O_WRONLY|O_CREAT|O_TRUNC, 0666);
    dup2(fd, 1);
    printf("hello hahahaha\n");
 return 0;
}
在理解重定向之后,我们直接使用close这种操作来实现重定向就显的较为暴力且存在很多不稳定因素,使用dup2就可以很好的解决这个问题,将oldfd拷贝到newfd,通过这种方式,我们就可以将内容printf到log.txt中。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1407843.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

山体滑坡监测预警系统-gnss位移监测站

GNSS山体滑坡位移监测站是一种利用全球导航卫星系统&#xff08;GNSS&#xff09;进行山体滑坡位移监测的设备。它通过接收和处理GNSS卫星信号&#xff0c;能够实时监测山体的位移变化&#xff0c;并将数据传输到后端系统进行分析和处理。 GNSS山体滑坡位移监测站具有高精度、…

基于springboot+vue的师生健康信息管理系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 研究背景…

java web mvc-03-JFinal

拓展阅读 Spring Web MVC-00-重学 mvc mvc-01-Model-View-Controller 概览 web mvc-03-JFinal web mvc-04-Apache Wicket web mvc-05-JSF JavaServer Faces web mvc-06-play framework intro web mvc-07-Vaadin web mvc-08-Grails JFinal JFinal 是基于 Java 语言的极…

CSC7225

CSC7225 为高性能电流模式 PWM 开关电源控制器&#xff0c;满足绿色环保标准&#xff1b;广泛适用于经济型开关电源&#xff0c;如 DVD、机顶盒、传真机、打印机、LCD 显示器等。CSC7225 采用 DIP-8 封装。 CSC7225主要特点  CSC7225内置 700V 高压功率开关管&#xff0c;外…

kubeadm 安装k8s集群后,master节点notready问题解决方案

使用kubeadm 安装k8s集群后&#xff0c;加载calico cni 网络组件后&#xff0c;master节点notready问题 表现为&#xff1a; 使用命令查看日志&#xff1a;journalctl -f -u kubelet 报错如下&#xff1a; Failed to start ContainerManager failed to initialize top level…

通过代理服务器的方式解决跨域问题

学习源码可以看我的个人前端学习笔记 (github.com):qdxzw/frontlearningNotes 觉得有帮助的同学&#xff0c;可以点心心支持一下哈 这里以本地访问https://heimahr.itheima.net/api/sys/permission接口为列子 Node.js 代理服务器 (server.js) 本次考虑使用JSONP或CORS代理来…

服务器配置优化句柄数量

当部署新的服务器环境时&#xff0c;需要对服务器的句柄数进行一次优化&#xff0c; 否则当用户量稍微增大可能会导致系统问题。 系统句柄数量 查看系统最大文件句柄数&#xff0c;执行命令&#xff1a;cat /proc/sys/fs/file-max&#xff0c;如果最大句柄数不能满足要求&am…

前端项目对接protobufjs的时候,踩坑总结

Protobuf&#xff08;Protocol Buffers&#xff09;是一种用于序列化结构化数据的语言无关、平台无关、可扩展的机制。在JS/TS项目中&#xff0c;使用WebSocket与Protobuf可以实现高效的通信和数据传输。protobufjs官方仓库:https://github.com/protobufjs/protobuf.js 安装pro…

列表的创建与删除

Python 中列表可以动态地添加、修改和删除元素&#xff0c;是 Python 编程中不可或缺的一部分。本文将介绍如何使用 Python 创建和删除列表&#xff0c;以及常用的方法和技巧。 创建列表 在 Python 中&#xff0c;我们可以使用一对方括号 [ ] 来创建一个空列表&#xff0c;也可…

瓦片地图编辑器——实现卡马克卷轴的编辑,键盘控制游戏移动和鼠标点击游戏编辑通过同一个视口实现。

左边是游戏地图编辑区&#xff0c;右边是地图缓冲区&#xff0c;解决了地图缓冲区拖动bug&#xff0c;成功使得缓冲区可以更新。 AWSD进行移动 鼠标左右键分别是绘制/拖动 按F1健导出为mapv3.txt F2清空数组 打印的是游戏数组 easyx开发devcpp 5.11 easyx20220922版本 #…

《GreenPlum系列》GreenPlum初级教程-GreenPlum详细入门教程

文章目录 GreenPlum详细入门教程第一章 GreenPlum介绍1.MPP架构介绍2.GreenPlum介绍3.GreenPlum数据库架构4.GreenPlum数据库优缺点 第二章 GreenPlum单节点安装1.Docker创建centos容器1.1 拉取centos7镜像1.2 创建容器1.3 进入容器1.4 容器和服务器免密操作1.4.1 生成密钥1.4.…

手动导入jar包到Maven的解决方案(简单有效!)

想要导入一个jar包到项目中&#xff0c;这个jar包在Maven中没有可以尝试以下方式。 第一步 先找到你maven的本地仓库&#xff0c;我的仓库就在这里&#xff0c;你可以根据你安装的maven找到你的目录 第二步 根据坐标创建文件夹。 这个依赖modbus4j.jar&#xff0c;Maven远…

TCP三握四挥(面试需要)

TCP建立连接需要三次握手过程&#xff0c;关闭连接需要四次挥手过程 三次握手 从图中可以看出&#xff0c;客户端在发起connect时&#xff0c;会发起第一次和第三次握手。服务端在接收客户端连接时&#xff0c;会发起第二次握手。 这三次握手&#xff0c;都会通过SYNACK的方式…

论文翻译:On Bringing Robots Home

On Bringing Robots Home 关于引入机器人到家庭 文章目录 On Bringing Robots Home关于引入机器人到家庭1 Introduction1 引言2 Technical Components and Method2 技术组件与方法2.1 Hardware Design2.1 硬件设计2.2 Pretraining Dataset – Homes of New York2.2 预训练数据…

AI研究必备!这些网站你不可不知

AI研究必备&#xff01;这些网站你不可不知 在人工智能的浪潮中&#xff0c;你是否感到手足无措&#xff1f;别担心&#xff0c;今天我就为大家揭晓那些AI研究者们的秘籍——他们常用的网站。这些网站不仅包含了丰富的资源&#xff0c;还能让你的研究之路更加顺畅。让我们一起…

numpy 多项式拟合函数polyfit的使用

import numpy as np def fit(x,y,m,w):if len(x)<m:return Falsexishu np.polyfit(x,y,m,ww)p np.poly1d(xishu) # 构造多项式yfit p(x) # 拟合的y值yresid y - yfit # 残差SSresid sum(pow(yresid, 2)) # 残差平方和SStotal len(y) * np.var(y) # 总体平均方差if SSt…

JAVA用Zxing生成的二维码扫码桩识别出现\000026

使用Zxing生成的二维码&#xff0c;扫码桩扫描偶先扫描出\000026 文章目录 [TOC](文章目录) 前言一、出现原因分析二、解决方式三、iso ECI 字符集编码说明 前言 Hutool QrCodeUtil&#xff08;底层Zxing&#xff09; 生成二维码扫码桩扫描二维码 出现类似&#xff1a;"\…

80.网游逆向分析与插件开发-背包的获取-自动化助手显示物品数据

内容参考于&#xff1a;易道云信息技术研究院VIP课 上一个内容&#xff1a;升级Notice类获得背包基址-CSDN博客 码云地址&#xff08;ui显示角色数据 分支&#xff09;&#xff1a;https://gitee.com/dye_your_fingers/sro_-ex.git 码云版本号&#xff1a;3be017de38c50653b1…

Linux: make/Makefile 相关的知识

背景&#xff1a; 会不会写makefile&#xff0c;从一个侧面说明了一个人是否具备完成大型工程的能力一个工程中的源文件不计数&#xff0c;其按类型、功能、模块分别放在若干个目录中&#xff0c;makefile定义了一系列的 规则来指定&#xff0c;哪些文件需要先编译&#xff0c…

【MySQL·8.0·源码】subquery 子查询处理分析(一)

引言 在 SQL 中&#xff0c;子查询属于 Nested Query 的一种形式&#xff0c;根据 Kim 的分类[1]&#xff0c;Nested Query 即嵌套查询是一种 SQL-like 形式的查询语句嵌套在另一 SQL 中&#xff0c;SQL-like 的嵌套子句可以出现在 SELECT、FROM 和 WHERE 子句的任意位置。 在…