Search code examples
cfileiofilesize

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


Solution

  • 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.