When reading in a file, it is often useful to know its size without relying on the EOF (for reasons Klausi mentioned). Here is a simple way to find filesize on a POSIX system:
Code:
#include <sys/types.h>
#include <sys/stat.h>
struct stat buf;
const char *path = "/home/jdeckard/testfile";
off_t filesize;
stat( path, &buf );
filesize = buf.st_size;
I'm not checking for errors for the sake of clarity, but make sure you do so in your application :) stat() will return -1 and set errno if something goes wrong.
Here is a less efficient, yet ANSI compliant, solution:
Code:
#include <stdio.h>
FILE *fptr;
int filesize;
fptr = fopen( "/home/jdeckard/testfile", "r" );
fseek( fptr, 0, SEEK_END );
filesize = ftell( fptr );
fclose( fptr );
If you decide not to close your file right away, keep in mind that the file descriptor refers to the end of the file. You will want to move it before doing any reads.