Linux函数之lseek、stat、lstat

发布时间 2023-03-27 10:27:26作者: nakejimamiyuki

Linux函数之lseek、stat、lstat的简单介绍

lseek函数

在Linux终端下输入命令:man 2 lseek,可以查看具体函数信息

    #include <sys/types.h>
    #include <unistd.h>

    off_t lseek(int fd, off_t offset, int whence);

    参数:
        - fd:文件描述符:通过open得到,用于操作文件
        - offset:偏移量
        - whence:
            SEEK_SET
              The file offset is set to offset bytes.

       SEEK_CUR
              The file offset is set to its current location plus offset bytes.

       SEEK_END
              The file offset is set to the size of the file plus offset bytes.
    
    返回值:
        返回文件指针的位置
    作用:
        1. 移动文件指针到头文件        lseek(fd,0,SEEK_SET);
        2. 获取文件当前指针的位置      lseek(fd,0,SEEK_CUR);
        3. 获取文件的长度             lseek(fd,0,SEEK_END);
        4. 拓展文件的长度             lseek(fd,100,SEEK_END);

下面为简单案例:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(){

    int fd = open("./hello.txt",O_WRONLY);
    if(fd == -1){
        perror("open");
        return -1;

    }

    //扩展文件
    int ret = lseek(fd,100,SEEK_END);
    if(ret == -1){
        perror("lseek");
        return -1;
    }

    //写入空数据
    write(fd,"mengyan",7);

    lseek(fd,12,SEEK_SET);
    write(fd,"miaomiao",8);

    //关闭文件
    close(fd);
    

    return 0;
}

stat函数

在Linux终端下输入命令:man 2 stat,可以查看具体函数信息

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

        int stat(const char *pathname, struct stat *statbuf);
            作用:获取一个文件的相关信息
            参数:
                - pathname:操作文件的路径
                - statbuf:结构体变量,传出参数,用于保存获取到的文件信息
            返回值:
                - 成功:返回0
                - 失败:返回-1,设置error

        int lstat(const char *pathname, struct stat *statbuf);
            作用:用于获取连接文件的信息

下面为简单案例:

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

int main(){

    struct stat statbuf;
    int ret = stat("./hello.txt",&statbuf);
    if(ret == -1){
        perror("stat");
        return -1;
    }

    std::cout << statbuf.st_size <<std::endl;

    return 0;
}

lstat函数

作用:用于获取链接文件的信息