C语言实现获取文件大小(字节数)

首先使用如下命令在当前文件夹,创建一个大小为1234578字节的空白文件:

fsutil file createnew ./test.bin 12345678

关于fsutil命令的介绍:Windows快速创建任意大小的空白文件

使用十六进制编辑器打开,可以看到内容全是0,长度为12345678字节:

C语言获取此文件的字节数:

#include "stdio.h"
#include "stdlib.h"
#include "stdint.h"

int get_file_size(uint8_t *path, uint32_t *size)
{
    FILE *fp = fopen((const char *)path, "rb");
    
    if(fp == NULL)
    {
        printf("file open faild!\n");
        return -1;
    }
    
    fseek(fp, 0, SEEK_END);
    *size = ftell(fp);
    fclose(fp);

    return 0;
}

int main(void)
{
    uint32_t size = 0;
    int ret = 0;
    uint8_t path[100] = "./test.bin";
    ret = get_file_size(path, &size);
    
    printf("%s size = %d byte, ret = %d\n", path, size, ret);
    
    return 0;
}

编译,运行:

$ gcc test.c

$ ./a.exe
./test.bin size = 12345678 byte, ret = 0
在 Linux 下,你可以通过读取 /proc/diskstats 文件来获取磁盘读写字节数。该文件包含了系统上所有磁盘的统计信息,包括读写次数、读写扇区数、读写时间、IO 请求处理时间等,每行对应一个磁盘设备。你可以使用 C 语言中的文件操作函数(如 fopen、fread、fclose 等)来读取该文件,并从中解析出你所需要的信息。 以下是一个简单的示例代码,用于获取指定磁盘设备的读写字节数: ``` #include <stdio.h> #define DISK_NAME "/dev/sda" // 指定磁盘设备 int main() { FILE *fp; char buf[256]; unsigned long long read_bytes, write_bytes; fp = fopen("/proc/diskstats", "r"); if (fp == NULL) { perror("Failed to open /proc/diskstats"); return 1; } while (fgets(buf, sizeof(buf), fp)) { char dev_name[32]; unsigned int major, minor, reads_completed, reads_merged, sectors_read, read_time; unsigned int writes_completed, writes_merged, sectors_written, write_time; if (sscanf(buf, "%u %u %s %u %u %u %u %u %u %u %u %u %u %u %llu %u %u %u %u", &major, &minor, dev_name, &reads_completed, &reads_merged, &sectors_read, &read_time, &writes_completed, &writes_merged, &sectors_written, &write_time, NULL, NULL, NULL, &read_bytes, NULL, NULL, NULL, &write_bytes) != 20) { continue; } if (strcmp(dev_name, DISK_NAME) == 0) { printf("Read bytes: %llu\nWrite bytes: %llu\n", read_bytes * 512, write_bytes * 512); break; } } fclose(fp); return 0; } ``` 需要注意的是,/proc/diskstats 文件中的所有数值都以扇区为单位,而一个扇区的大小通常为 512 字节。因此,为了获取读写字节数,你需要将读取到的扇区数乘以 512。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

whik1194

如果对你有帮助,欢迎打赏。谢谢

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

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

打赏作者

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

抵扣说明:

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

余额充值