user200340
user200340

Reputation: 3371

How to get a file length in c?

I just have a quick question about how to get the length of a file containing hexadecimal numbers. For example:

724627916C

The only way I can think is to convert hex value to binary:

724627916C => 0111001001000110001001111001000101101100

then count the bits of binary value. Just wondering if this is the correct way? Thanks

Upvotes: 1

Views: 26782

Answers (5)

SSpoke
SSpoke

Reputation: 5836

File length in C goes use the function _filelength()

#include <io.h>

int fn, fileSize;
FILE * f = fopen(&String, "rb");
if (f)
{
  fn = _fileno(f);
  fileSize = _filelength(fn);
}
fclose(f);

Upvotes: 0

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36977

In un*x-like operating systems, stat can be used for that purpose.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

If you want to count the bits, it would be simpler to set up an array that tells you how many bits are set in each hex digit (indexed by character code), and then add things up without explicitly converting to binary.

Assuming C99:

static bits_map[256] =
{
    ['0'] = 0, ['1'] = 1, ['2'] = 1, ['3'] = 2,
    ['4'] = 1, ['5'] = 2, ['6'] = 2, ['7'] = 3,
    ['8'] = 1, ['9'] = 2,
    ['a'] = 2, ['b'] = 3, ['c'] = 2, ['d'] = 3,
    ['e'] = 3, ['f'] = 4,
    ['A'] = 2, ['B'] = 3, ['C'] = 2, ['D'] = 3,
    ['E'] = 3, ['F'] = 4,
};

size_t n_bits = 0;
int c;
while ((c = getchar()) != EOF)
    n_bits += bits_map[c];

printf("Number of bits set: %zd\n", n_bits);

Upvotes: 0

shartte
shartte

Reputation: 756

No, this is not the correct way.

FILE *fp = fopen("filename", "rb");
fseek(fp, 0, SEEK_END);
int lengthOfFile = ftell(fp);
fclose(fp);

In principle: Open a file, seek to the end and retrieve your current position. What you'll get is the number of bytes in the file.

Edit: Your question is a little unclear. Do you want to retrieve the number of bytes in the file, or the number of bytes represented by the hexadecimal string in the file? If the latter is the case, and you don't have any whitespaces in your file, just divide the number of bytes returned by the method above by 2.

Upvotes: 16

jheddings
jheddings

Reputation: 27553

Try this answer for some help. If that doesn't work, Google has plenty of information on determining file size in C.

Upvotes: 1

Related Questions