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

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

fsutil file createnew ./test.bin 12345678

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

使用十六进制编辑器打开,可以看到内容全是0,长度为12345678字节:
C语言实现获取文件大小(字节数)_第1张图片
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

你可能感兴趣的:(C语言,文件大小,字节)