LINUX文件操作函数

目录

1.open()

//1.打开已有文件(无需指定权限)

int open(const char *pathname, int flags);

//2.打开/创建文件(创建时必须指定mode权限)

int open(const char *pathname, int flags, mode_t mode);

2.close()

int close(int fd);

成功:返回 0(表示文件描述符已成功释放,内核关闭对应文件句柄);

失败:返回 -1(表示关闭失败,文件描述符可能仍未释放),同时内核会设置全局错误码errno,用于排查失败原因。

perror()

Bad file descriptor 传入无效 fd(如 - 1、已关闭的 fd)

Interrupted system call close 执行时被信号中断(少见)

I/O error 关闭时发生底层 I/O 错误(罕见)

复制代码
#include <stdio.h>
#include <string.h>
#include <sys/types.h>  // 定义mode_t、dev_t等open依赖的基础数据类型
#include <sys/stat.h>   // 定义文件权限常量(如S_IRUSR)、stat结构体
#include <fcntl.h>      // 声明open函数原型,定义所有打开标志(如O_RDONLY)
#include <unistd.h>  // 声明close()、read()、write()等文件操作函数
#include <errno.h>   // 定义错误码(如ENOENT文件不存在)
#include <stdio.h>   // 配合perror()打印直观的错误信息

void main(int argc, const char *argv[])
{
    //第一个参数 不写路径默认当前路径下文件
    //第二个参数 文件不存在则创建新文件
    //创建新文件需要第三个参数,默认权限0666
    if(argc != 2)
    {
        printf("参数输入错误!\n");
        printf("usage: a.out <dst_file>\n");
        return -1;
    }
    int fd;
    //文件不存在创建文件,文件存在报错;
    fd = open(argv[1], O_RDONLY|O_CREAT|O_EXCL, 0666);
    if(fd == -1)
    {
        perror("文件打开失败!");
        // printf("errno:%d\n", errno);
        if(errno == EEXIST)
        {
            printf("文件已存在!\n");
        }
        return -1;
    }
    printf("文件打开成功!\n");
    int close_fd;

    close_fd = close(fd);
    if(close_fd == -1)
    {
        printf("文件关闭失败!\n");
        return -1;
    }
    return 0;
}

3.read()

ssize_t read(int fd, void *buf, size_t count);

返回值

n > 0 成功读取n个字节(n ≤ count) 继续处理缓冲区中的n个字节数据(注意:不一定能读到 count 个字节)

n = 0 到达文件末尾(EOF),无数据可读 停止读取,关闭文件描述符

n = -1 读取失败 检查errno判断失败原因,分情况处理

复制代码
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>   
#include <unistd.h>   // 包含close函数原型
#include <errno.h>    //errno函数原型

void main(int argc, const char *argv[])
{
    //第一个参数 不写路径默认当前路径下文件
    //第二个参数 文件不存在则创建新文件
    //创建新文件需要第三个参数,默认权限0666
    if(argc != 2)
    {
        printf("参数输入错误!\n");
        printf("usage: a.out <dst_file>\n");
        return -1;
    }
    int fd;
    //文件不存在创建文件,文件存在报错;
    fd = open(argv[1], O_RDONLY);
    if(fd == -1)
    {
        perror("文件打开失败!");
        // printf("errno:%d\n", errno);
        if(errno == EEXIST)
        {
            printf("文件已存在!\n");
        }
        return -1;
    }
    printf("文件打开成功,文件描述符%d\n", fd);
    //读取文件数据
    char read_buf[1024] = {0};
    int readback_date = 0;
    readback_date = read(fd, read_buf, sizeof(read_buf));
    if(fd == -1)
    {
        perror("文件读取失败!\n");
        return -1;
    }
    printf("文件读取成功\n");
    printf("%s\n", read_buf);


    close(fd);
    return 0;
}

4.write()

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

fd int 有效文件描述符(open/creat返回的非负整数),必须是可写模式打开(O_WRONLY/O_RDWR/O_APPEND)

buf const void * 存储待写入数据的内存缓冲区指针,const表示 write 不会修改缓冲区内容,不能是 NULL

count size_t 期望写入的字节数(非负整数),通常设为缓冲区中有效数据的长度(如字符串用 strlen (buf))

复制代码
#include <sys/types.h>   // open依赖的基础数据类型
#include <sys/stat.h>    // open依赖的权限常量
#include <fcntl.h>       // open函数声明、打开标志(如O_WRONLY/O_APPEND)
#include <errno.h>       // 定义错误码,排查write失败原因
#include <stdio.h>       // 配合perror()打印直观的错误信息
#include <string.h>      // 可选,用于strlen()计算字符串长度
#include <stdio.h>
#include <string.h>
#include <unistd.h>   // 包含close函数原型


void main(int argc, const char *argv[])
{
    //第一个参数 不写路径默认当前路径下文件
    //第二个参数 文件不存在则创建新文件
    //创建新文件需要第三个参数,默认权限0666
    if(argc != 2)
    {
        printf("参数输入错误!\n");
        printf("usage: a.out <dst_file>\n");
        return -1;
    }
    int fd;
    ssize_t ret_wr = 0;
    struct student
    {
        char name[10];
    };

    //读写方式打开文件
    //文件不存在创建文件,文件存在报错;
    //文件存在则清空文件内容
    fd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666);
    if(fd == -1)
    {
        perror("文件打开失败!");
        return -1;
    }
    printf("文件打开成功,文件描述符%d\n", fd);
    //向文件写入数据
    int value = 100;
    char str_buf[] = "hello book!";
    //写入整数
    // ret_wr = write(fd, &value, sizeof(value));
    // if(ret_wr == -1)
    // {
    //     perror("写入失败:");
    //     return -1;
    // }
    // printf("整数写入成功!\n");

    //写入字符串
    // ret_wr = write(fd, str_buf, strlen(str_buf));
    // if(ret_wr == -1)
    // {
    //     perror("写入失败:");
    //     return -1;
    // }
    //printf("字符串写入成功!\n");

    //写入结构体
    struct student stu = {"张三22"};
    ret_wr = write(fd, &stu, sizeof(str_buf));
    if(ret_wr == -1)
    {
        perror("写入失败:");
        return -1;
    }
    printf("结构体写入成功!\n");

    //读取文件数据
    // char read_buf[1024] = {0};
    // int readback_date = 0;
    // readback_date = read(fd, read_buf, sizeof(read_buf));
    // if(fd == -1)
    // {
    //     perror("文件读取失败!\n");
    //     return -1;
    // }
    // printf("文件读取成功\n");
    // printf("%s\n", read_buf);

    close(fd);
    return 0;
}
相关推荐
葵续浅笑2 小时前
从Spring拦截器到Filter过滤器:一次报文修改加解密的填坑经验
java·后端·spring
XW01059992 小时前
4-11判断素数
前端·python·算法·素数
J2虾虾2 小时前
Spring Boot中使用@Scheduled做定时任务
java·前端·spring boot
浅念-2 小时前
C++ 继承
开发语言·c++·经验分享·笔记·学习·算法·继承
算法备案代理2 小时前
深度合成算法备案:生成式AI需要备案吗?
人工智能·算法·算法备案
菜鸡儿齐2 小时前
leetcode-全排列
算法·leetcode·深度优先
czxyvX2 小时前
017-Linux-网络基础概念
linux·网络
Wect2 小时前
LeetCode 102. 二叉树的层序遍历:图文拆解+代码详解
前端·算法·typescript
不想看见4042 小时前
Maximal Square 基本动态规划:二维--力扣101算法题解笔记
算法·leetcode·动态规划