Search code examples
linuxfileiofilesize

How to get the file length in C on Linux?


I'm looking for the equivalent of Microsoft's _filelength in Linux. I tried this, but it's incorrect.

long _filelength(char *f)
{
    struct stat st;
    stat(f, &st);
    return st.st_size;
}

if((hfile = fopen("data.arp","rb"))!=NULL)
    fsize = _filelength(fileno(hfile));

How do I get the file length in C on Linux?


Solution

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