POSIX
POSIX 标准有自己的方法来获取文件大小。
包含sys/stat.h 标头以使用该函数。
概要
示例
注意:它将大小限制为4GB。如果不是Fat32 文件系统,则使用 64 位版本!
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat info;
stat(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat64 info;
stat64(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
ANSI C(标准)
ANSI C 不直接提供确定文件长度的方法。
我们将不得不使用我们的头脑。现在,我们将使用 seek 方法!
概要
示例
#include <stdio.h>
int main(int argc, char** argv)
{
FILE* fp = fopen(argv[1]);
int f_size;
fseek(fp, 0, SEEK_END);
f_size = ftell(fp);
rewind(fp); // to back to start again
printf("%s: size=%ld", (unsigned long)f_size);
}
如果文件是stdin 或管道。 POSIX、ANSI C 不起作用。
如果文件是管道,它将返回 0 或 stdin。
意见:
您应该改用 POSIX 标准。因为,它支持 64 位。