i need to check whether the file has previous data stored in it
There might be no portable and robust way to do that (that file might change during the check, because other processes are using it). For example, on Unix or Linux, that file might be opened by another process writing into it while your own program is running (and that might even happen between your ftell
and your rewind
). And your program might be running in several processes.
You could use operating system specific functions. For POSIX (including Linux and many Unixes like MacOSX or Android), you might use stat(2) to query the file status (including its size with st_size
). But after that, some other process might still write data into that file.
You might consider advisory locking, e.g. with flock(2), but then you adopt the system-wide convention that every program using that file would lock it.
You could use some database with ACID properties. Look into sqlite or into RDBMS systems like PostGreSQL or MariaDB. Or indexed file library like gdbm.
You can continue coding with the implicit assumption (but be aware of it) that only your program is using that file, and that your program has at most one process running it.
if the file is empty [...] how can the file pointer not be NULL
?
As Increasingly Idiotic answered, fopen
can fail, but usually don't fail on empty files. Of course, you need to handle fopen
failure (see also this). So most of the time, your fp
would be valid, and your code chunk (assuming no other process is changing that file simulateously) using ftell
and rewind
is an approximate way to check that the file is empty. BTW, if you read (e.g. with fread
or fgetc
) something from that file, that read would fail if your file was empty, so you probably don't need to check its emptiness before.
A POSIX specific way to query the status (including size) of some fopen
-ed file is to use fileno(3) and fstat(2) together like fstat(fileno(fp), &mystat)
after having declared struct stat mystat;