Skip to content

Instantly share code, notes, and snippets.

@jakekara
Created May 10, 2017 14:18
Show Gist options
  • Select an option

  • Save jakekara/c4ae2fc2ba4ec210252a184eece4c2d2 to your computer and use it in GitHub Desktop.

Select an option

Save jakekara/c4ae2fc2ba4ec210252a184eece4c2d2 to your computer and use it in GitHub Desktop.
Get a file size two ways -- using lseek and using stat.
/*
* determine a file's size with lseek
*/
#include <unistd.h> /* for lseek */
#include <stdio.h> /* for printf */
#include <fcntl.h> /* for open */
int main(int ac, char *av[])
{
if ( ac < 2 ) return 0;
int fd = open(av[1],O_RDONLY); /* 1 syscall */
int size = lseek(fd, 0, SEEK_END); /* 2 syscalls */
printf("%d\n", size);
close(fd); /* 3 syscalls */
return 0;
}
/*
* determine a file's size with stat
*/
#include <sys/stat.h> /* for stat */
#include <stdio.h> /* for printf */
int main(int ac, char *av[])
{
if ( ac < 2 ) return 0;
struct stat stbuf;
stat( av[1], &stbuf); /* 1 syscall */
printf ("%lld\n", stbuf.st_size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment