user1091856
user1091856

Reputation: 3158

Function that returns file size?

int filesize(FILE * handle)
{
    int filesize;
    int old_pointer = ftell(handle);
    fseek(handle, 0, SEEK_END);
    filesize = ftell(handle);
    fseek(handle, old_pointer, SEEK_SET);
    return filesize;
}

Is this a good way for a function to return the size of a file?

Upvotes: 0

Views: 292

Answers (4)

user149341
user149341

Reputation:

I'd personally use a function from the stat family, like so. Also, note that int may be too small for the return value (especially on 32-bit systems); off_t is guaranteed to work.

off_t filesize(FILE *handle) {
    struct stat statbuf;
    if (fstat(fileno(handle), &statbuf) != 0) {
        // handle an error
    } else {
        return statbuf.st_size;
    }
}

Note also that this can be easily tweaked to work for files that aren't open yet by using standard stat() instead of fstat().

Upvotes: 1

Kevin
Kevin

Reputation: 56049

Use stat:

#include <sys/stat.h>

int stat(const char *path, struct stat *buf);

struct stat {
           dev_t     st_dev;     /* ID of device containing file */
           ino_t     st_ino;     /* inode number */
           mode_t    st_mode;    /* protection */
           nlink_t   st_nlink;   /* number of hard links */
           uid_t     st_uid;     /* user ID of owner */
           gid_t     st_gid;     /* group ID of owner */
           dev_t     st_rdev;    /* device ID (if special file) */
--->       off_t     st_size;    /* total size, in bytes */
           blksize_t st_blksize; /* blocksize for file system I/O */
           blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
           time_t    st_atime;   /* time of last access */
           time_t    st_mtime;   /* time of last modification */
           time_t    st_ctime;   /* time of last status change */
};

Upvotes: 0

shinkou
shinkou

Reputation: 5154

You could use stat() or fstat() if you were on *nix.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

It is one way to do it, as long as your files aren't too big (which, for a 32-bit system or Windows 64-bit, means not more than 2 GiB). It has the merit of more or less working on any platform. Of course, ftell() returns a long, not an int (so on a 64-bit non-Windows system, the files it can report on are much bigger, as long as you fix your code appropriately). However, requiring four function calls is a trifle expensive.

The POSIX alternatives are stat(), lstat() and fstat().

There will be analogues in the Windows API.

Upvotes: 2

Related Questions