View Single Post
Old Feb 21st, 2005, 3:17 PM   #1
tempest
Programming Guru
 
tempest's Avatar
 
Join Date: Oct 2004
Posts: 1,041
Rep Power: 6 tempest is on a distinguished road
Send a message via ICQ to tempest Send a message via AIM to tempest Send a message via Yahoo to tempest
Determilning file-size in C (code snippet)

This is more of a code snippet than a tutorial... if you have any questions i'll be more than happy to answer them though.

#include <stdio.h>

void error(char *errMsg);

int main(int argc, char *argv[]) {
    if(argc != 2) {
        char errMsg[1024];
        snprintf(errMsg, 1024, "Usage: %s <filename>\n", argv[0]);
        error(errMsg);
    }


    FILE *fl = fopen(argv[1], "r");

    if(fl == NULL) {
        char errMsg[1024];
        snprintf(errMsg, 1024, "Could not open file \"%s\"\n", argv[1]);
        error(errMsg);
    }

    fseek (fl, 0, SEEK_END);
    long size = ftell(fl);
    fclose(fl);

    printf("%s:\n", argv[1]);
    printf("    %.2f Megabytes\n", (double)size/1048576);
    printf("    %.2f Kilobytes\n", (double)size/1024);
    printf("    %d Bytes\n", size);

    return 0;
}

void error(char *errMsg) {
    printf("%s", errMsg);
    exit(0);
}
__________________

tempest is offline   Reply With Quote