Suraya Suraya - 1 month ago 6
C Question

Getting a file's size in C with lseek?

I am trying to get the size of a file in C with the following operations... I am new to C

This is my struct mem at the top of my file:

struct mem {size_t size;
};


Is this the correct set up with local variables/return statements and such?

struct mem* fileSize(char* filename)
{
currentPos = lseek(filename, (size_t)0, SEEK_CUR);
size = lseek(filename, (size_t)0, SEEK_END);
lseek(filename, currentPos, SEEK_SET); // seek back to the beginning of file
return size;
}

Answer

From what can be observed, perhaps you would like to know how to pass the filesize back to the caller in a 'mem' structure (of your own design). This is certainly possible; however the 'fileSize()' function will have to supply memory in which to return this 'mem' struct. Perhaps something like:

struct mem* fileSize(char* filename)
{
   struct mem *m = malloc(sizeof(*m));

Add the line above to allocate memory of suitable size.

... and perhaps a small oversite... lseek() does not take a filename as it's first parameter. Rather it requires a 'file descriptor', which can be obtained (from a filename) by implementing 'open()':

   int fd = open(filename, O_RDONLY);

Now, fd can be passed to 'lseek()', instead of the filename.

   off_t currentPos = lseek(fd, (size_t)0, SEEK_CUR);
   m->size = lseek(fd, (size_t)0, SEEK_END);

'm' is a 'struct mem *' where you can now store the size.

   lseek(fd, currentPos, SEEK_SET);   // seek back to the beginning of file

And don't forget to close the file when finished:

   close(fd);

   return(m);

The allocated and initialized 'm' is returned to the caller (with m->size).

}

The caller (of fileSize) should 'free()' the (struct mem) memory when finished with it to prevent a memory leak.