1

如何使用 C 计算文件的字节数?

假设下面的文件中包含一些代码(数据)。字数统计 (wc) 程序如何计算指定文件的确切字节数?

例如,如果我们有以下文件:

#include<stdio.h>

int main(void) {
    printf("helloworld!");
}

我想知道如何创建一个可以计算该文件中字节数的程序。

此文件的字节数为 64,使用 Linux 字数 (wc)

cat helloworld.cpp | wc -c
64
4

1 回答 1

8

stat(2)作为样本的摘录

char filename[] = "helloworld.cpp";
struct stat sb;

if (stat(filename, &sb) == -1) {
    perror("stat");
}
else {
    printf("File size:                %lld bytes\n",
           (long long) sb.st_size);
}

或者,您可以使用getc()函数

int bytes;
for(bytes = 0; getc(stdin) != EOF; ++bytes);
printf("File size:                %d bytes\n",bytes);
于 2014-09-01T23:10:38.947 回答