Linux中对文件的操作(一)

linux中对文件进行操作

open函数

*int open(const char pathname, int flags);
pathname:指的是文件名
flags:权限 只读打开O_RDONLY 只写打开O_WRONLY 可读可写打开O_RDWR 以上三个参数中应当只指定一个。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>


int main(){
//int open(const char *pathname, int flags);
        int fd;
        fd = open("./file1",O_RDWR);

        printf("fd = %d\n",fd);	//返回3,若file1不存在则返回-1
        return 0;
}

下面的参数是可以选择的:
O_CREAT 若文件不存在则创建它,使用这个选项时,需要同时说明第三个参数mode,用其说明该文件的存取许可权限。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main(){
        int fd;
        fd = open("./file1",O_RDWR);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT,0600);	//可读 r 4 可写 w 2 可执行 x 1;6=4+2 可读可写
                if(fd > 0){
                        printf("open file success!\n");
                }
        }
        return 0;
}

O_EXCL 如果同时指定了O_CREAT,而文件已经存在,则出错使fd=-1;

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main(){
        int fd;

        fd = open("./file1",O_RDWR|O_CREAT|O_EXCL,0600);
        if(fd == -1){
                printf("file cunzai\n");
        }
        return 0;
}

运行结果:
file cunzai
因为当前目录中已经存在file1这个文件了。如果此时不存在,则运行这段代码不会报错,因此运行结果不会有任何反应。
O_APPEND 每次写都加到文件的尾端
在我们正常使用write写入数据时,会将自己的数据覆盖之前的数据(区别于O_TRUNC,O_APPEND不会清空之前的数据,而是覆盖之前的字节,如果之前的数据多于新写入的数据,那么多的部分不会被清空),如果我们想要在之前的基础上写入数据,就需要用到这个参数

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(){
        int fd;
        char *buf = "wlw is so handsome";
        fd = open("./file1",O_RDWR|O_APPEND);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT|O_APPEND,0600);
                if(fd > 0){
                        printf("create file success!\n");
                }
        }
        printf("open success! fd = %d\n",fd);

        //ssize_t write(int fd, const void *buf, size_t count);
        write(fd,buf,strlen(buf));

        close(fd);


        return 0;
}

运行之后,会在原来的基础上换行写入数据。

O_TRUNC 打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(){
        int fd;
        char *buf = "test";
        fd = open("./file1",O_RDWR|O_TRUNC);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT|O_APPEND,0600);
                if(fd > 0){
                        printf("create file success!\n");
                }
        }
        printf("open success! fd = %d\n",fd);

        //ssize_t write(int fd, const void *buf, size_t count);
        write(fd,buf,strlen(buf));

        close(fd);


        return 0;
}

加入O_TRUNC参数会把原先的内容清空,再加入自己需要的内容。
此外open函数还可以添加第三个参数,mode_t mode,一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限。

write函数

*ssize_t write(int fd, const void buf, size_t count);
fd 通过open函数后,会返回一个文件描述符fd
buf 缓冲区
count 写入文件的大小
将缓冲区buf中的数据写count个字符进入到fd指向的文件中写入成功时,返回写入的字节数,读取失败返回-1.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(){
        int fd;
        char *buf = "hello world!";
        fd = open("./file1",O_RDWR);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT,0600);
                if(fd > 0){
                        printf("create file success!\n");
                }
        }
        printf("open success! fd = %d\n",fd);

        //ssize_t write(int fd, const void *buf, size_t count);
        write(fd,buf,strlen(buf));

        close(fd);


        return 0;
}

注意:在本段代码中,如果将write的第三个参数修改为sizeof(buf)只会显示8个字符,因为buf属于指针类型,sizeof(buf)只会分配指针的大小,在linux系统中为指针分配的8字节大小。

close

int close(int fd);
只需给出文件的fd即可关闭该文件

read

*ssize_t read(int fd, void buf, size_t count);
将fd指向文件的count大小的字符读入到buf中去。读取成功时,返回读取的字节数,读取失败返回-1.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(){
        int fd;
        char *buf = "wlw is handsome";
        fd = open("./file1",O_RDWR);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT,0600);
                if(fd > 0){
                        printf("create file success!\n");
                }
        }
        printf("open success! fd = %d\n",fd);

        //ssize_t write(int fd, const void *buf, size_t count);
        int n_write = write(fd,buf,strlen(buf));
        if(n_write != -1){
                printf("write %d byte to file\n",n_write);
        }

        char *readBuf;
        readBuf = (char *)malloc(sizeof(char)*n_write);
        //ssize_t read(int fd, void *buf, size_t count);
        int n_read = read(fd,readBuf,n_write);
        printf("read:%d byte,context:%s\n",n_read,readBuf);

        close(fd);


        return 0;
}

执行后会显示
open success! fd = 3
write 15 byte to file
read:1 byte,context:

内容被不能被读取出来,这就涉及了光标的问题,当我们写入字符后,光标会在最后一位上,那此时我们进行read操作,只会从最后开始读,自然什么也读不到。因此我们需要将光标移到头,或者重新打开。

重新打开解决光标问题


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(){
        int fd;
        char *buf = "wlw is handsome";
        fd = open("./file1",O_RDWR);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT,0600);
                if(fd > 0){
                        printf("create file success!\n");
                }
        }
        printf("open success! fd = %d\n",fd);

        //ssize_t write(int fd, const void *buf, size_t count);
        int n_write = write(fd,buf,strlen(buf));
        if(n_write != -1){
                printf("write %d byte to file\n",n_write);
        }

        close(fd);      //关闭
        fd = open("./file1",O_RDWR);    //重新打开

        char *readBuf;
        readBuf = (char *)malloc(sizeof(char)*n_write);
        //ssize_t read(int fd, void *buf, size_t count);
        int n_read = read(fd,readBuf,n_write);
        printf("read:%d byte,context:%s\n",n_read,readBuf);

        close(fd);


        return 0;
}

运行结果为:
open success! fd = 3
write 15 byte to file
read:15 byte,context:wlw is handsome
在write写完之后进行关闭重新打开,此时光标会回到第一个位置,就可以通过read进行读取,解决了光标的问题。

光标移动操作解决光标问题

lseek

off_t lseek(int fd, off_t offset, int whence);
将fd指向文件的文件读写指针(光标)相对whence移动offset个字节
whence:可以选择
SEEK_SET:头
SEEK_END :尾
SEEK_CUR:当前位置

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(){
        int fd;
        char *buf = "wlw is handsome";
        fd = open("./file1",O_RDWR);

        if(fd == -1){
                printf("open file failed!\n");
                fd = open("./file1",O_RDWR|O_CREAT,0600);
                if(fd > 0){
                        printf("create file success!\n");
                }
        }
        printf("open success! fd = %d\n",fd);

        //ssize_t write(int fd, const void *buf, size_t count);
        int n_write = write(fd,buf,strlen(buf));
        if(n_write != -1){
                printf("write %d byte to file\n",n_write);
        }

        //off_t lseek(int fd, off_t offset, int whence);        
        lseek(fd,0,SEEK_SET);	//移动光标
        char *readBuf;
        readBuf = (char *)malloc(sizeof(char)*n_write);
        //ssize_t read(int fd, void *buf, size_t count);
        int n_read = read(fd,readBuf,n_write);
        printf("read:%d byte,context:%s\n",n_read,readBuf);

        close(fd);


        return 0;
}

运行结果:
open success! fd = 3
write 15 byte to file
read:15 byte,context:wlw is handsome
另外在修改光标位置时,也可以利用SEEK_CUR或者SEEK_END来进行偏移,注意!偏移量为正数时向后偏移,偏移量为负数时向前偏移。

利用lseek函数来计算文件大小

lseek的返回值为当前光标较文件起始位置的偏移量,因此我们可以用lseek来计算出文件大小:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(){
        int fd;
        char *buf = "wlw is handsome";

        fd = open("./file1",O_RDWR);

        int filesize = lseek(fd,0,SEEK_END);
        printf("file size is :%d\n",filesize);

        close(fd);


        return 0;
}

运行结果:
file size is :15

creat

*int creat(const char pathname, mode_t mode);
根据创建模式(权限)创建文件
creat常见创建模式:
宏表示 数字
S_IRUSR 4 可读
S_IWUSR 2 可写
S_IXUSR 1 可执行
S_IRWXU 7 可读、写、执行

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(){
        int fd;
        char *buf = "wlw is handsome";


        //int creat(const char *pathname, mode_t mode);
        fd = creat("./file1",S_IRWXU);
        printf("creat file1 success!\n");
        fd = open("./file1",O_RDWR);
        write(fd,buf,strlen(buf));
        printf("write file1 success!\n");
        return 0;
}

最后分享几个在linux命令行中的快捷操作
复制 yy
多行复制 行数+yy
粘贴 p
撤回 u
重做 Ctrl+r
删除整行 dd
删除大段代码 d+↓
缩进 左:<<
右:>>
多行缩进 行数+<<或者行数+>>

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

总分420+专业140+哈工大哈尔滨工业大学803信号与系统和数字逻辑电路考研电子信息与通信工程,真题,大纲,参考书。

考研复习一路走来&#xff0c;成绩还是令人满意&#xff0c;专业803信号和数电140&#xff0c;总分420&#xff0c;顺利上岸&#xff0c;总结一下自己这一年复习经历&#xff0c;希望大家可以所有参考&#xff0c;这一年复习跌跌拌拌&#xff0c;有时面对压力也会焦虑&#xff…

【软件设计师】上午题

【软考】软件设计师plus 「软件设计师」 2022年下半年上午真题解析视频 计算机系统知识 22下 考点&#xff1a;指令系统之CISC vs RISC RISC指令系统整体特点是简单、精简 》指令种类少&#xff0c;但是指令功能强 考点&#xff1a;计算机系统组成 A属于运算器&#xff0c;…

第四节课《XTuner作业》

Tutorial/xtuner/personal_assistant_document.md at camp2 InternLM/Tutorial GitHub Tutorial/xtuner/personal_assistant_document.md at camp2 InternLM/Tutorial GitHub GitHub - InternLM/Tutorial at camp2 视频链接&#xff1a;https://b23.tv/BrTSfsl PDF链接&a…

【Delphi 爬虫库 3】使用封装好的 HTML 解析库对 HTML 数据进行解析

文章目录 解析HTML的意义1、简单解析HTML代码2、实战解析HTML代码 解析HTML的意义 HTML是Web页面的构建语言&#xff0c;每个Web开发者都需要了解HTML的基础知识。但是&#xff0c;通过手动阅读和解析需要极大的心智和时间投入。这时候&#xff0c;我们就需要使用HTML在线解析…

Mac 电脑安装 Raptor 流程图软件的方法

0. 安装逻辑 &#xff08;1&#xff09;运行 raptor&#xff0c;本质上需要 mac 能够运行 windows 程序&#xff0c;因此需要安装 .NET Runtime 7.0&#xff0c;这是微软程序运行必须的文件。 &#xff08;2&#xff09;运行 raptor 还需要安装依赖文件 mono-libgdiplus。 &am…

【C++】一篇文章带你熟练掌握<智能指针>及其模拟实现

目录 一、引入 二、智能指针的使用及原理 1、RAII 2、智能指针的原理 3、auto_ptr 4、unique_ptr 5、shared_ptr 6、weak_ptr 一、引入 我们先分析一下为什么需要智能指针&#xff1f; double Division(int a, int b) {// 当b 0时抛出异常if (b 0){throw invalid_a…

Day30:热帖排行、生成长图、将文件上传到云服务器、优化热门帖子列表、压力测试

热帖排行 不同的算分方式&#xff1a; 只存变化的帖子到redis中&#xff0c;每五分钟算一次分&#xff0c;定时任务 存redis 构建redis键 //统计帖子分数 //key:post:score -> value:postId public static String getPostScoreKey() {return PREFIX_POST SPLIT "…

【解决】docker一键部署报错

项目场景见&#xff1a;【记录】Springboot项目集成docker实现一键部署-CSDN博客 问题&#xff1a; 1.docker images 有tag为none的镜像存在。 2.有同事反馈&#xff0c;第一次启动docker-compose up -d 项目无法正常启动。后续正常。 原因&#xff1a; 1.服务中指定了镜像m…

mqtt上行数据传送

{"id": "123","version": "1.0","params": {"wendu": {"value": 25.0},"humi": {"value": 23.6}} } 不要time!!!!!!!!!!!!!!!!!!!!!!!!!!! 下面是官方文档的代码&#xff0c;我用…

自制RAG工具:docx文档读取工具

自制RAG工具&#xff1a;docx文档读取工具 1. 介绍2. 源码2.1 chunk2.2 DocReader 3. 使用方法3.1 文档格式设置3.2 代码使用方法 1. 介绍 在RAG相关的工作中&#xff0c;经常会用到读取docx文档的功能&#xff0c;为了更好地管理文档中的各个分块&#xff0c;以提供更高质量的…

伺服电机初识

目录 一、伺服电机的介绍二、伺服电机的基本原理三、伺服电机的技术特点四、伺服电机的分类五、实际产品介绍1、基本技术规格&#xff1a;2、MD42电机硬件接口3、通讯协议介绍3.1 通讯控制速度运行3.2 通讯控制位置运行3.3 通讯控制转矩运行 4、状态灯与报警信息 一、伺服电机的…

MyScaleDB:SQL+向量驱动大模型和大数据新范式

大模型和 AI 数据库双剑合璧&#xff0c;成为大模型降本增效&#xff0c;大数据真正智能的制胜法宝。 大模型&#xff08;LLM&#xff09;的浪潮已经涌动一年多了&#xff0c;尤其是以 GPT-4、Gemini-1.5、Claude-3 等为代表的模型你方唱罢我登场&#xff0c;成为当之无愧的风口…

富文本编辑器CKEditor4简单使用-07(处理浏览器不支持通过工具栏粘贴问题 和 首行缩进的问题)

富文本编辑器CKEditor4简单使用-07&#xff08;处理浏览器不支持通过工具栏粘贴问题 和 首行缩进的问题&#xff09; 1. 前言——CKEditor4快速入门2. 默认情况下的粘贴2.1 先看控制粘贴的3个按钮2.1.1 工具栏粘贴按钮2.1.2 存在的问题 2.2 不解决按钮问题的情况下2.2.1 使用ct…

Linux——基础IO2

引入 之前在Linux——基础IO(1)中我们讲的都是(进程打开的文件)被打开的文件 那些未被打开的文件呢&#xff1f; 大部分的文件都是没有被打开的文件&#xff0c;这些文件在哪保存&#xff1f;磁盘(SSD) OS要不要管理磁盘上的文件&#xff1f;(如何让OS快速定位一个文件) 要…

设计模式之拦截过滤器模式

想象一下&#xff0c;在你的Java应用里&#xff0c;每个请求就像一场冒险旅程&#xff0c;途中需要经过层层安检和特殊处理。这时候&#xff0c;拦截过滤器模式就化身为你最可靠的特工团队&#xff0c;悄无声息地为每一个请求保驾护航&#xff0c;确保它们安全、高效地到达目的…

Endnote X9 20 21如何把中文引用的et al 换(变)成 等

描述 随着毕业的临近&#xff0c;我在写论文时可能会遇到在引用的中文参考文献中出现“et al”字样。有的学校事比较多&#xff0c;非让改成等等&#xff0c;这就麻烦了。 本身人家endnote都是老美的软件&#xff0c;人家本身就是针对英文文献&#xff0c;你现在让改成等等&a…

JavaScript的操作符运算符

前言&#xff1a; JavaScript的运算符与C/C一致 算数运算符&#xff1a; 算数运算符说明加-减*乘%除/取余 递增递减运算符&#xff1a; 运算符说明递增1-- 递减1 补充&#xff1a; 令a1&#xff0c;b1 运算a b ab12ab22ab--10a--b00 比较(关系)运算符&#xff1a; 运算…

【ChatGPT with Date】使用 ChatGPT 时显示消息时间的插件

文章目录 1. 介绍2. 使用方法2.1 安装 Tampermonkey2.2 安装脚本2.3 使用 3. 配置3.1 时间格式3.2 时间位置3.3 高级配置(1) 生命周期钩子函数(2) 示例 4. 反馈5. 未来计划6. 开源协议7. 供给开发者自定义修改脚本的文档7.1 项目组织架构7.2 定义新的 Component(1) 定义一个新的…

提示找不到msvcr110.dll怎么办,分享多种靠谱的解决方法

当用户在操作计算机时遇到系统提示“找不到msvcr110.dll&#xff0c;无法继续执行代码”这一错误信息&#xff0c;这个问题会导致软件无法启动运行。本文将介绍计算机找不到msvcr110.dll的5种详细的解决方法&#xff0c;帮助读者解决这个问题。 一&#xff0c;关于msvcr110.dll…

《十六》QT TCP协议工作原理和实战

Qt 是一个跨平台C图形界面开发库&#xff0c;利用Qt可以快速开发跨平台窗体应用程序&#xff0c;在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置&#xff0c;实现图形化开发极大的方便了开发效率&#xff0c;本章将重点介绍如何运用QTcpSocket组件实现基于TCP的网络通信…
最新文章