【Linux系统编程(文件编程)】之读、写文件、文件光标移动

news2024/9/21 18:35:03

文章目录

  • 一、文件写入
  • 二、文件读取
  • 三、文件光标移动
    • 使用 `lseek()` 计算文件大小

一、文件写入

在这里插入图片描述
write() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd.write()
write() 函数,将从buf缓冲区开始,写count个字节,写入到文件描述符fd引用的文件

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

int main()
{
        int fd;
        char *buf = "changxianrui hen shuai !!!";
        fd = open("./file", O_RDWR);
        if(fd == -1){
                printf("open file failed\n");
                fd = open("./file", O_RDWR|O_CREAT, 0600);
                if(fd > 0)
                {
                        printf("create file success");
                }
        }
        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;
}

在这里插入图片描述
strlen()函数用来统计字符串的长度,遇到\0结束统计,即函数返回值不包括\0。例如:strlen("abc")的返回值为3,但是sizeof("abc")的返回值是4,这里要留意。

二、文件读取

如果读取不到内容可能是光标的问题 重新打开或者移动光标

在这里插入图片描述
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
read() 从文件描述符fd,读取count个字节的数据,存到buf缓冲区。

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

int main()
{
        int fd;
        char *buf = "changxianrui hen shuai !!!";
        fd = open("./file", O_RDWR);
        if(fd == -1){
                printf("open file failed\n");
                fd = open("./file", 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 bytes to file\n", n_write);
        }


        close(fd);


        fd = open("./file", O_RDWR);
        char *readBuf;
        readBuf = malloc(sizeof(char) * n_write + 1);  // 没有这步段错误
//      ssize_t read(int fd, void *buf, size_t count);
        int n_read = read(fd, readBuf, n_write);
        printf("read %d bytes, context:%s\n", n_read, readBuf);
        close(fd);
        return 0;
}

三、文件光标移动

lseek()函数的作用:让文件指针相对whence参数移动offest字节,offest为正数则向后移动,反之负数向前移。

文件指针是你在这个文件中所处的位置,进行读写操作的时候,都是从文件指针所在的位置开始。

在这里插入图片描述
lseek()函数的返回值是距离文件头的字节数。

可以利用移动光标读文件。因为先写文件,后读文件,移动光标避免读不到。

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

int main()
{
        int fd;
        char *buf = "changxianrui hen shuai !!!";
        fd = open("./file", O_RDWR);
        if(fd == -1){
                printf("open file failed\n");
                fd = open("./file", 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 bytes to file\n", n_write);
        }


        char *readBuf;
        readBuf = malloc(sizeof(char) * n_write + 1);  // 没有这步段错误
//      ssize_t read(int fd, void *buf, size_t count);
//      off_t lseek(int fd, off_t offset, int whence);
        //lseek(fd, 0, SEEK_SET);
        lseek(fd, -26, SEEK_END);//正数向后移动,负数向后移动
        int n_read = read(fd, readBuf, n_write);
        printf("read %d bytes, context:%s\n", n_read, readBuf);
        close(fd);
        return 0;
}

使用 lseek() 计算文件大小

在这里插入图片描述

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

int main()
{
        int fd;
        fd = open("./file", O_RDWR);
        int size = lseek(fd, 0, SEEK_END);//正数向后移动
        printf("read %d bytes\n", size);
        close(fd);
        return 0;
}

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

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

相关文章

开发实例:Spring Boot、MyBatis和Layui打造增删改查项目

目录导航 1. 技术栈介绍1.1 Springboot1.2 MyBatis1.3 Layui 2. 开发环境2.1 前端示例代码2.2 后端示例代码2.3 数据库建表语句 3. 项目截图4. 运行截图4.1 查询界面4.2 新增界面4.3 修改界面4.4 删除界面 5. 小结6. 完整代码下载 通过学习这个实例项目&#xff0c;我们将积累点…

[HarekazeCTF2019]baby_rop2

小白垃圾笔记&#xff0c;不建议阅读。 这道题学到了两个思想吧&#xff1a; 1.一个是有的函数泄露libc打印不写出来。 2.另一个是printf函数的利用吧。 3.栈对齐好像是只有system有。 分析下题目吧&#xff1a; 64位 绕过nx 本来以为第10行&#xff0c;有坑呢。结果好像是…

简单三招教你音频怎么翻译

随着世界全球化的加速发展和文化交流的增多&#xff0c;音频翻译这项技术变得越来越重要。在国际商务和学术会议中&#xff0c;语言的沟通至关重要。不同国家或地区的参与者会用不同的语言进行交流&#xff0c;这时候&#xff0c;使用音频翻译就可以帮助他们更好地沟通&#xf…

2023年最强测试工程师Linux面试题及答案

前言&#xff1a; 大家好&#xff0c;前段时间有很多朋友给我私信留言&#xff1a;在面试软件测试工作时&#xff0c;部分的liunx的问题答不上来&#xff0c;于是雷叔快马加鞭&#xff0c;连夜给大家整理了一份关于linux的面试题&#xff0c;请看好了。 正文&#xff1a; 1.三…

算法分析基础

问题&#xff1a;如何比较不同算法的性能&#xff1f; 分析算法的运行时间 算法分析的原则 归纳基本操作 如:运算、赋值、比较 统一机器性能 假设基本操作代价均为1 统一机器性能后&#xff0c;算法运行时间依赖于问题输入规模与实例 相同输入规模&#xff0c…

python神经网络实现手写数字识别实验

手写数字识别实验是机器学习中最常见的一个示例&#xff0c;可以有很多种办法实现&#xff0c;最基础的其实就是利用knn算法&#xff0c;根据数字图片对应矩阵与经过训练的数字进行距离计算&#xff0c;最后这个距离最短&#xff0c;那么就认为它是哪个数字。 这里直接通过神经…

项目的延伸

目录 推送模块 1.表 1.1 表字段 1.2 字段类型 1.3 索引 1.4 关联查询 2.参数的含义 3.以技术流的维度讲业务逻辑 4.redis 4.1基础知识 5.设计模式 5.1策略模式 5.2工厂模式 6.遇到的问题 6.1稳定性 7.锁 即时通讯模块 1.表 1.1 表字段 1.2 字段类型 1.3 索…

关于队头阻塞的一些笔记

一、队头阻塞&#xff08;Head-of-Line Blocking&#xff0c;HOL&#xff09; 看到队头&#xff0c;联想到了数据结构课程中学到的队列&#xff0c;队列的一个特点就是FIFO&#xff08;First In First Out&#xff09;&#xff0c;即先进入队列的数据先出队列。所以&#xff0…

【Linux高级 I/O(6)】存储映射 I/O进阶应用(附代码示例)

mprotect()函数 使用系统调用 mprotect()可以更改一个现有映射区的保护要求&#xff0c;其函数原型如下所示&#xff1a; #include <sys/mman.h>int mprotect(void *addr, size_t len, int prot);参数 prot 的取值与 mmap()函数的 prot 参数的一样&#xff0c;m…

Pycharm 配置jupyter notebook 且Windos 安装vim编辑器

请记住要想让你的python成功安装jupyter notebook &#xff0c;你的python最好使用p大于等于python3.7 最好不要在python2大版本中安装jupyternotebook 这个会报错&#xff0c;需要你改一些配置文件&#xff0c;除非你想挑战一下自己&#xff0c;不过后面我会尝试在python2大版…

NeRF-VAE:将场景看作一个分布【ICML‘2021】

文章目录 GQN网络介绍Amortized InferenceNeRF-VAE GQN网络介绍 论文标题&#xff1a;Neural scene representation and rendering 作者&#xff1a;S. M. Ali Eslami, Danilo Jimenez Rezende, et al. 期刊&#xff1a;Science 发表时间&#xff1a;2018/06/15 该文章提出…

单视觉L2市场「鲶鱼」来了,掀起数据反哺高阶新打法

作者 | 张祥威编辑 | 德新 智驾方案的降本行动仍在推进。 早年&#xff0c;单视觉L2市场的玩家以Mobileye、博世为主&#xff0c;后来国内智驾公司加入&#xff0c;共同推动 1V、1R1V、nR1V等不同的方案兴起&#xff0c;L2近乎成为车辆的必备功能。 当下&#xff0c;在行业降低…

认识linux文件系统/文件夹名字解释

linux系统因为其高效、直接的底层操作而被很多代码开发者使用&#xff0c;谈及linux&#xff0c;大家普遍的印象就是黑乎乎的终端命令行&#xff0c;后来基于linux系统开发出来的具有可视化桌面的ubuntu版本&#xff0c;让大家的使用体验兼顾了windows系统的直观性可linux系统代…

YOLOV5使用(一): docker跑通,详解TensorRT下plugin的onnx

yolov5的工程使用(以人员检测为案例) 使用ubuntu为案例 docker run --gpus all -it -p 6007:6006 -p 8889:8888 --name my_torch -v $(pwd):/app easonbob/my_torch1-pytorch:22.03-py3-yolov5-6.0使用端口映射功能也就是说打开jupyter lab的指令是 http://localhost:8889/l…

windows先的conda环境复制到linux环境

如果是迁移的环境一致&#xff1a;同是windows或同是linux直接用这个命令即可&#xff1a; conda create -n new_env_name --clone old_env_path 如果是window的环境迁移到linux这种跨环境就不能用上面的方法&#xff0c;网上这方面的资料也很多&#xff0c;记录一下我的…

小蝌蚪找妈妈:Python之作用域链与 LEGB 原则

文章目录 参考描述作用域对象全局作用域globals() 局部作用域locals() 包含作用域内置作用域builtins 模块builtins 模块与 \_\_builtins__builtins is \_\_builtins__??? \_\_builtins__ 与内置作用域赶不走的 \_\_builtins__ 作用域链作用域链 与 LEGB 原则狗急跳墙之法 参…

【Go语言从入门到实战】基础篇

Go语言从入门到实战 — 基础篇 First Go Program 编译 & 运行 基本程序结构 应用程序入口 package mainimport "fmt"func main() {fmt.Println("Hello World") }退出返回值 package mainimport ("fmt""os" )func main() {fmt.Pr…

哪个产品功能重要?KANO模型帮你

哪个产品功能重要&#xff1f;KANO模型来帮你 模型工具可以协助思考和系统化改进 KANO模型是小日本一个教授提出 趣讲大白话&#xff1a;往往&#xff0c;怎么思考&#xff0c;比思考什么重要 【趣讲信息科技175期】 **************************** 东京理工大学教授狩野纪昭(No…

【医学图像】图像分割系列.2 (diffusion)

介绍几篇使用diffusion来实现医学图像分割的论文&#xff1a;DARL&#xff08;ICLR2023&#xff09;&#xff0c;MedSegDiff&#xff08;MIDL2023&#xff09;& MedSegDiff-V2&#xff08;arXiv2023&#xff09;&#xff0c;ImgX-DiffSeg&#xff08;arXiv2023&#xff09;…

CTF 2015: Search Engine-fastbin_dup_into_stack

参考&#xff1a; [1]https://gsgx.me/posts/9447-ctf-2015-search-engine-writeup/ [2]https://blog.csdn.net/weixin_38419913/article/details/103238963(掌握利用点&#xff0c;省略各种逆向细节) [3]https://bbs.kanxue.com/thread-267876.htm&#xff08;逆向调试详解&am…