Thread: file size in c

  1. #1
    Registered User
    Join Date
    Dec 2002

    file size in c

    is there a function to get lenght of a file in C

    i am in linux and filelength would not work

  2. #2
    Registered User
    Join Date
    Apr 2002
    Just create a file pointer like normal. Than use fseek to go to the end of the file. Then use ftell to let you know where it is. This should be correct for the file size. Just make sure to seek back to the beginning of the file before reading!
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

  3. #3
    Registered User moi's Avatar
    Join Date
    Jul 2002
    exactly what mr wizard said:

    // might not be 101% correct
    long length;
    FILE *bleh = fopen ("somefile", "rb");
    fseek (bleh, 0, SEEK_END);
    length = ftell (bleh);
    rewind (bleh);
    // now start reading
    hello, internet!

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >This should be correct for the file size.
    Don't expect an exact byte count though, this technique is only effective on binary files and even then the count may be approximate due to different end of line representations. Most of the time you don't really need to know the size of a file, just read it and take the size as you go.

    My best code is written with the delete key.

  5. #5
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Or use the (non-portable) stat function:
    #include <stdio.h>
    #include <sys/stat.h>
    int main(int argc, char *argv[])
       struct stat buf;
       if(stat(argv[0], &buf) == -1)
          return -1;
          printf("File size = %ld bytes\n", buf.st_size);
          return 0;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. archive format
    By Nor in forum A Brief History of
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM