Aditya Raj
Aditya Raj

Reputation: 1

Getting file size with lseek command in c

I was asked to find the size of the file usjng lseek command (without using stat) and i wrote the following code

int main()
{
    char buf[100], fn[10];
    int fd, i;
    printf("Enter file name\n");
        scanf("%s", fn);
    fd = open(fn, O_RDONLY);
    int size = lseek(fd, 0, SEEK_END);
    printf("Size is %d", size);
    close(fd);
}

But i am getting -1 as file size, where am i going wrong

Upvotes: 0

Views: 3354

Answers (2)

user3629249
user3629249

Reputation: 16540

the following proposed code:

  1. cleanly compiles
  2. properly checks for errors
  3. performs the desired functionality
  4. uses proper variable typing

and now the proposed code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main( void )
{
    char fn[10];
    int fd;
    printf("Enter file name\n");
    if( scanf("%9s", fn) != 1 )
    {
        fprintf( stderr, "scanf for file name failed\n" );
        exit( EXIT_FAILURE );
    }

    if( (fd = open(fn, O_RDONLY) ) < 0 )
    {
        perror( "open failed" );
        exit( EXIT_FAILURE );
    }

    off_t  size = lseek(fd, 0, SEEK_END);
    printf("Size is %ld", size);
    close(fd);
}

Upvotes: 1

P.W
P.W

Reputation: 26800

From lseek documentation available online:

RETURN VALUE        
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error.

So you have to check the errno (print it if lseek returns -1):

The list of possible errors from the same link:

ERRORS

   EBADF  fd is not an open file descriptor.  
   EINVAL whence is not valid.  Or: the resulting file offset would be
          negative, or beyond the end of a seekable device.  
   ENXIO  whence is SEEK_DATA or SEEK_HOLE, and the file offset is
          beyond the end of the file.  
   EOVERFLOW  The resulting file offset cannot be represented in an off_t.  
   ESPIPE fd is associated with a pipe, socket, or FIFO.  

In your case, it is most likely EBADF.

Upvotes: 1

Related Questions