How to count number of bytes in a file using C?

Stuxnet78 picture Stuxnet78 · Sep 2, 2014 · Viewed 16k times · Source

How to count the number of bytes for a file using C?

Suppose the file below contains some code (data) in it. How does the word count (wc) program count the exact number of bytes for the specified file?

So for example if we have the following file:

#include<stdio.h>

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

I would like to know how to create a program that can count the number of bytes in that file.

The number of bytes for this file is 64 using Linux word count (wc)

cat helloworld.cpp | wc -c
64

Answer

πάντα ῥεῖ picture πάντα ῥεῖ · Sep 2, 2014

As an excerpt from the stat(2) sample

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);
}

Alternatively you can use the getc() function

int bytes;
for(bytes = 0; getc(stdin) != EOF; ++bytes);
printf("File size:                %d bytes\n",bytes);