博客
关于我
二、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/

    你可能感兴趣的文章
    Panalog 日志审计系统 sprog_upstatus.php SQL 注入漏洞复现(XVE-2024-5232)
    查看>>
    pandas -按连续日期时间段分组
    查看>>
    pandas :to_excel() float_format
    查看>>
    pandas :将多列汇总为一列,没有最后一列
    查看>>
    pandas :将时间戳转换为 datetime.date
    查看>>
    pandas :将行取消堆叠到新列中
    查看>>
    pandas DataFrame 中的自定义浮点格式
    查看>>
    Pandas DataFrame 的 describe()方法详解-ChatGPT4o作答
    查看>>
    Pandas DataFrame中删除列级的方法链接解决方案
    查看>>
    Pandas DataFrame中的列从浮点数输出到货币(负值)
    查看>>
    Pandas DataFrame中的列从浮点数输出到货币(负值)
    查看>>
    Pandas Dataframe的日志文件
    查看>>
    pandas Groupby:创建两列的Groupby时,如何按正确的顺序对工作日进行排序?
    查看>>
    Pandas matplotlib 无法显示中文
    查看>>
    Pandas Plots:周末的单独颜色,x 轴上漂亮的打印时间
    查看>>
    Pandas 中的多索引旋转
    查看>>
    Pandas 中的日期范围
    查看>>
    pandas 中的时间序列箱线图
    查看>>
    Pandas 使用指南
    查看>>
    pandas 分组并使用最小值更新
    查看>>