Linux环境下,使用C语言获取文件字节数,文件大小(两种方法)

4 篇文章 0 订阅
3 篇文章 0 订阅
本文详细介绍了在Linux系统中使用lseek函数进行文件定位和stat函数获取文件属性的方法,包括参数解释、示例代码以及stat结构体的详细说明。
摘要由CSDN通过智能技术生成

目录

方法一:使用lseek函数

lseek函数详解

方法二:使用stat函数(推荐)

stat结构体详解


方法一:使用lseek函数

lseek函数详解

#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
返回:若成功则返回新的文件位移量(绝对偏移量,相对于文件的头),若出错为-1
功能:定位一个已打开的文件

参数

  • fd:已打开文件的文件描述符
  • offset:位移量
  • whence:定位的位置
    • SEEK_SET:将该文件的位移量设置为距文件开始处 offset个字节。
    • SEEK_CUR:将该文件的位移量设置为其当前值加offset,offset可为正或负。
    • SEEK_END:将该文件的末尾长度加offset,offset可为正或负。空洞文件(标准写法)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

int main()
{
    int fd = open("../file/hello.txt", O_WRONLY);
    if (fd == -1)
    {
        perror("open error");
        return -1;
    }
    int lseek_ret = lseek(fd, 0, SEEK_END);
    if (close(fd) == -1)
    {
        perror("close error");
        return -1;
    }
    printf("lseek_ret = %d\n", lseek_ret);
    return 0;
}

方法二:使用stat函数(推荐)

int stat(const char *pathname, struct stat *statbuf);

参数:(不需要文件描述符

        pathname:文件路径

        statbuf:(传出参数)存放文件属性

stat结构体详解

struct stat
{
    dev_t     st_dev;     /* ID of device containing file */文件使用的设备号
    ino_t     st_ino;     /* inode number */    索引节点号 
    mode_t    st_mode;    /* protection */  文件对应的模式,文件,目录等
    nlink_t   st_nlink;   /* number of hard links */    文件的硬连接数  
    uid_t     st_uid;     /* user ID of owner */    所有者用户识别号
    gid_t     st_gid;     /* group ID of owner */   组识别号  
    dev_t     st_rdev;    /* device ID (if special file) */ 设备文件的设备号
    off_t     st_size;    /* total size, in bytes */ 以字节为单位的文件容量   
    blksize_t st_blksize; /* blocksize for file system I/O */ 包含该文件的磁盘块的大小   
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */ 该文件所占的磁盘块  
    time_t    st_atime;   /* time of last access */ 最后一次访问该文件的时间   
    time_t    st_mtime;   /* time of last modification */ /最后一次修改该文件的时间   
    time_t    st_ctime;   /* time of last status change */ 最后一次改变该文件状态的时间   
};

st_size表示大小

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

int main(int argc, char *argv[])
{
    int fd = open("../file/hello.txt", O_WRONLY);
    if(fd == -1)
    {
        perror("open error");
        return -1;
    }
    struct stat file_inf;
    memset(&file_inf, 0, sizeof(file_inf));

    stat(argv[1], &file_inf);

    printf("%s的文件大小是%ld", argv[1], file_inf.st_size);

    return 0;
}

  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aogu181

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值