lseek,stat函数

399 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

lseek函数

Linux操作系统中的lseek函数用于更改文件描述符的文件偏移量。它在unistd.h头文件中定义。

fd参数是要更改文件偏移量的文件的文件描述符。offset参数是要移动文件偏移量的字节数。whence参数指定如何解释offset参数。

  • SEEK_SEToffset设置为文件开头处的offset字节。
  • SEEK_CURoffset设置为其当前位置加上offset字节。
  • SEEK_ENDoffset设置为文件大小加上offset字节。
    标准C库的函数
    #include<stdio.h>
    int fseek(FILE*stream, long offset, int whence);

    Linux系统函数
    #include<sys/types.h>
    #include<unistd.h>
    off_t lseek(int fd, off_t offset, int whence);
        参数
            -fd:文件描述符,通过open得到的,通过这个fd操作某个文件
            -offset: 偏移量
            - whence:
                SEEK_SET
                    设置文件指针的偏移量
                SEEK_CUR
                    设置偏移量:当前位置+第二个参数offset的值
                SEEK_END
                    设置偏移量:文件大小+第二个参数offset的值
        返回值:返回文件指针的位置

    作用:
        1.移动文件指针到文件头
        lseek(fd, 0, SEEK_SET);
        
        2.获取当前文件指针的位置
        lseek(fd, 0, SEEK_CUR);

        3.获取文件长度
        lseek(fd, 0, SEEK_END);

        4.拓展文件的长度,当前文件10b,110b,增加了100个字节
        lseek(fd, 100, SEEK_END);
        //注意:写一次数据

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

int main() {
    int fd = open("hello.txt", O_RDWR);
    
    if (fd == -1) {
        perror("open");
        return -1;
    }

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

    //写入一个空数据
    write(fd, " ", 1);

    //关闭文件
    close(fd);

    return 0;
}

stat函数

Linux操作系统中的stat函数用于获取文件的信息。它在sys/stat.h头文件中定义。

pathname参数是一个字符串,指定要获取信息的文件的路径。buf参数是指向struct stat结构的指针,该结构将存储文件的信息。

struct stat结构包含以下成员:

  • st_mode: 文件类型和访问权限。
  • st_ino: 文件的inode编号。
  • st_dev: 文件所在设备的设备编号。
  • st_nlink: 文件的硬链接数。
  • st_uid: 文件的所有者的用户ID。
  • st_gid: 文件的所有者的组ID。
  • st_size: 文件的大小(以字节为单位) 等等
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

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

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

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

    printf("size: %ld\n", statbuf.st_size);
    return 0;
}