Pregunta

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;
}
¿Fue útil?

Solución

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.

Otros consejos

You can use POSIX function stat(2) to find out the size of a file directly. If you want to only use Standard C Library functions, then you should use fseek(3) and ftell(3).

lseek() does not work from a filename. It expects an integer file handle. Try stat() instead. Additionally, don't use a pointer return value. Something like this:

size_t fileSize(char* filename)
{
    size_t rv = 0;  // I like to return 0, if badness occurs
    struct stat  file_info;

    if ( (filename != NULL) && (stat(filename,&file_info) == 0) )  //NULL check/stat() call
      rv = (size_t)file_info.st_size;  // Note: this may not fit in a size_t variable

  return rv;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top