你如何确定在C文件的大小? [英] How do you determine the size of a file in C?

查看:136
本文介绍了你如何确定在C文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能找出一个文件的大小,以字节为单位?

 的#include<&stdio.h中GT;unsigned int类型的fsize(字符*文件){
  //发生的事情吗?
}


解决方案

根据NilObject的code:

 的#include< SYS / stat.h>off_t FSIZE(为const char *文件名){
    struct stat中ST;    如果(STAT(文件名,和放大器; ST)== 0)
        返回st.st_size;    返回-1;
}

的变化:


  • 所做的文件名参数的为const char

  • 修正了 struct stat中定义,它是缺失的变量名。

  • 返回 1 上的错误,而不是 0 ,这将是暧昧的空文件。 off_t 是一个符号类型,所以这是可能的。

如果你想 FSIZE()来打印错误的信息,您可以使用此:

 的#include< SYS / stat.h>
#包括LT&;&string.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&errno.h中GT;off_t FSIZE(为const char *文件名){
    struct stat中ST;    如果(STAT(文件名,和放大器; ST)== 0)
        返回st.st_size;    fprintf中(标准错误,无法确定%s的尺寸:%S \\ n,
            文件名,字符串错误(错误));    返回-1;
}

在32位系统上,你应该用选项 -D_FILE_OFFSET_BITS = 64 编译它,否则, off_t 只会持有价值高达2 GB。见在Linux中详情大文件支持。

How can I figure out the size of a file, in bytes?

#include <stdio.h>

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

解决方案

Based on NilObject's code:

#include <sys/stat.h>

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

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

    return -1; 
}

Changes:

  • Made the filename argument a const char.
  • Corrected the struct stat definition, which was missing the variable name.
  • Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible.

If you want fsize() to print a message on error, you can use this:

#include <sys/stat.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;
}

On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.

这篇关于你如何确定在C文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆