博客
关于我
二、Linux文件操作示例
阅读量:83 次
发布时间:2019-02-26

本文共 1755 字,大约阅读时间需要 5 分钟。

Linux文件操作示例

Linux系统文件操作主要通过系统调用函数来实现。本文将介绍常用文件操作函数及其使用方法。

系统文件API函数

在使用文件操作函数之前,需先包含必要的头文件:

#include 
#include
#include

文件创建

使用creat函数创建文件:

int creat(const char *filename, mode_t mode);
  • filename:文件名称(字符串形式)
  • mode:文件权限模式
  • 返回值:成功返回0,失败返回-1

文件打开

使用open函数打开文件:

int open(const char *pathname, int flags);int open(const char *pathname, int flags, mode_t mode);
  • pathname:文件名称(字符串形式)
  • flags:打开模式(读模式需设置O_RDONLY,写模式需设置O_RDWRO_WRONLY
  • mode:文件权限模式(可选)
  • 返回值:文件描述符

文件读取

使用read函数读取文件内容:

int read(int fd, const void *buf, size_t length);
  • fd:文件描述符
  • buf:用于存储读取数据的缓冲区
  • length:要读取的数据长度
  • 返回值:实际读取的数据长度

文件写入

使用write函数写入文件:

int write(int fd, const void *buf, size_t length);
  • fd:文件描述符
  • buf:写入数据的缓冲区
  • length:写入的数据长度
  • 返回值:成功返回0,失败返回-1

文件关闭

使用close函数关闭文件:

int close(int fd);
  • fd:文件描述符
  • 返回值:成功返回0,失败返回-1

文件定位

使用lseek函数定位文件指针:

int lseek(int fd, offset_t offset, int whence);
  • fd:文件描述符
  • offset:定位的位置(字节偏移量)
  • whence:定位方式(SEEK_SETSEEK_CURSEEK_END
  • 返回值:成功返回0,失败返回-1

文件操作流程

读操作流程

  • 打开文件
  • 读取文件内容
  • 关闭文件
  • 写操作流程

  • 打开文件
  • 写入文件
  • 关闭文件
  • 示例代码

    写文件函数

    void write_file(char *s) {    int fd;    fd = open("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); // 创建并打开文件    if (fd > 0) {        write(fd, s, sizeof(s));        close(fd);    } else {        // 处理打开失败的情况    }}

    读文件函数

    int read_file(char *s, int len) {    int fd, rtn_len;    fd = open("hello.txt", O_RDWR); // 读取文件    rtn_len = read(fd, s, len); // 读取文件内容    close(fd); // 关闭文件    return rtn_len;}

    主函数

    int main() {    char testbuf[100] = {0}; // 初始化缓冲区    int len; // 用于存储读取的长度    // 写操作    write_file("hello guoguo\n");    // 读操作    len = read_file(testbuf, 100); // 读取文件内容到缓冲区    testbuf[len] = '/'; // 添加分隔符    printf("Reading File Content: %s", testbuf); // 输出结果}

    以上代码示例展示了如何使用Linux系统文件操作函数进行文件读写操作。通过合理使用这些函数,可以实现文件的创建、读取、写入和关闭等基本操作。

    转载地址:http://vxwu.baihongyu.com/

    你可能感兴趣的文章
    php & 和 & (主要是url 问题)
    查看>>
    php -- 魔术方法 之 判断属性是否存在或为空:__isset()
    查看>>
    php -- 魔术方法 之 获取属性:__get()
    查看>>
    php -树-二叉树的实现
    查看>>
    PHP -算法-二路归并
    查看>>
    php 2条不一样 的json数据 怎么放在一个json里面_如果你是PHP开发者,请务必了解一下Composer...
    查看>>
    php 360 不记住密码,JavaScript_多种方法实现360浏览器下禁止自动填写用户名密码,目前开发一个项目遇到一个很 - phpStudy...
    查看>>
    regExp的match、exec、test区别
    查看>>
    php 404 自定义,APACHE 自定义404错误页面设置方法
    查看>>
    PHP 5.3.0以上推荐使用mysqlnd驱动
    查看>>
    php aes sha1解密,PHP AES加密/解密
    查看>>
    php CI框架单个file表单多文件上传例子
    查看>>
    reflow和repaint引发的性能问题
    查看>>
    php csv 导出
    查看>>
    php curl 实例+详解
    查看>>
    php curl_init函数用法(http://blog.sina.com.cn/s/blog_640738130100tsig.html)
    查看>>
    php curl_multi批量发送http请求
    查看>>
    php echo 输出 锘?... 乱码问题
    查看>>
    ReferenceQueue的使用
    查看>>
    Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig
    查看>>