简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM