如何计算文件大小(以字节为单位)?

#include <stdio.h>

unsigned int fsize(char* file){
  //what goes here?
}

最佳答案

基于NilObject的代码:

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

off_t fsize(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1;
}

变化:
  • 将filename参数设为const char
  • 更正了struct stat定义,该定义缺少变量名。
  • 错误时返回-1而不是0,这对于一个空文件来说是模棱两可的。 off_t是带符号的类型,因此这是可能的。

  • 如果您希望fsize()在错误时显示一条消息,则可以使用以下命令:
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <string.h>
    #include <stdio.h>
    #include <errno.h>
    
    off_t fsize(const char *filename) {
        struct stat st;
    
        if (stat(filename, &st) == 0)
            return st.st_size;
    
        fprintf(stderr, "Cannot determine size of %s: %s\n",
                filename, strerror(errno));
    
        return -1;
    }
    

    在32位系统上,应使用-D_FILE_OFFSET_BITS=64选项进行编译,否则off_t将仅保留2 GB以下的值。有关详细信息,请参见Large File Support in Linux的“使用LFS”部分。

    关于c - 您如何确定C中文件的大小?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8236/

    10-12 14:51
    查看更多