我们如何确定C中文件的大小?
如何计算文件大小(以字节为单位)?
#include <stdio.h> unsigned int fsize(char* file){ //what goes here? }
解决方案
回答
我们将需要使用库函数来检索文件的详细信息。由于C完全独立于平台,因此我们需要让我们知道我们要开发的平台/操作系统!
回答
如果我们可以使用std c库,则可以:
#include <sys/stat.h> off_t fsize(char *file) { struct stat filestat; if (stat(file, &filestat) == 0) { return filestat.st_size; } return 0; }
回答
我们可以打开文件,使用以下命令将文件底部相对于偏移量设置为0
#define SEEKBOTTOM 2 fseek(handle, 0, SEEKBOTTOM)
从fseek返回的值是文件的大小。
我已经很长时间没有使用C编写代码了,但是我认为它应该可以工作。
回答
Matt的解决方案应该可以工作,除了它是C ++而不是C,而且不需要初始告诉。
unsigned long fsize(char* file) { FILE * f = fopen(file, "r"); fseek(f, 0, SEEK_END); unsigned long len = (unsigned long)ftell(f); fclose(f); return len; }
也为我们固定了支架。 ;)
更新:这并不是真正的最佳解决方案。在Windows上,文件大小限制为4GB,它可能比仅使用平台特定的调用(如GetFileSizeEx或者stat64)要慢。
回答
**不要这样做(为什么?):
Quoting the C99 standard doc that i found online: "Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.**
将定义更改为int,以便可以发送错误消息,然后使用fseek()和ftell()确定文件大小。
int fsize(char* file) { int size; FILE* fh; fh = fopen(file, "rb"); //binary mode if(fh != NULL){ if( fseek(fh, 0, SEEK_END) ){ fclose(fh); return -1; } size = ftell(fh); fclose(fh); return size; } return -1; //error }
回答
在Google中进行的快速搜索找到了一种使用fseek和ftell的方法,以及一个带有此问题的线程,并给出了答案,它不能用另一种方式仅使用C来完成。
我们可以使用可移植性库,例如NSPR(为Firefox提供支持的库),也可以检查其实现(相当麻烦)。
回答
不要使用int
。如今,大小超过2 GB的文件很常见
不要使用unsigned int
。大小超过4 GB的文件很常见,是一些不太常见的污垢
IIRC标准库将off_t定义为无符号的64位整数,这是每个人都应该使用的。几年后,当我们开始挂起16 EB文件时,我们可以将其重新定义为128位。
如果我们使用的是Windows,则应使用GetFileSizeEx,它实际上使用带符号的64位整数,因此它们将开始遇到8艾字节文件的问题。愚蠢的微软! :-)
回答
而且,如果我们要构建Windows应用程序,请使用GetFileSizeEx API,因为CRT文件的I / O杂乱无章,特别是对于确定文件长度,由于不同系统上文件表示的特殊性;)
回答
基于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; }
变化:
- 将文件名参数设为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以下的值。有关详细信息,请参见Linux中大文件支持的"使用LFS"部分。