Link to home
Start Free TrialLog in
Avatar of downatone
downatone

asked on

Opening empty files...

Hi there, assuming this should be a pretty simple question. Given it a few tries but to no avail! I'm trying to check if a file I'm opening is empty, but can't figure out how to do it. Any pointers?

FILE* ptr;
ptr = fopen("text.txt","r");

Sum her up:
How do I check if the text.txt file has nothing in it?

cheers
David
ASKER CERTIFIED SOLUTION
Avatar of GaryFx
GaryFx

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of downatone
downatone

ASKER

Gary,
Thanks for the quick reply.
Works great, just one more little thing sorry :)
When I go to replace "text.txt" with an actual file pointer:

FILE* filePtr;
filePtr = fopen("text.txt","r");

...
rc = stat(filePtr, &buf);
...

I'm getting this compile error:
tmp.c:23: warning: passing arg 1 of `stat' from incompatible pointer type

Any further thoughts?
cheers
David
No worries, found a way around that...still if you do have an answer I'm curious as too how you found a way around it??? cheers
Hmm.  I've never really thought about that.  You can use open instead of fopen to create the file, passing the resulting descriptor to fstat to get the information, and passing the same descriptor to fdopen to get a FILE*.  But I don't know of any way to get a file descriptor from a stream file (FILE*) pointer (which seems silly).  

You could in theory address the original problem by attempting to read one byte, and figuring out whether or not it returns.  But then you'd either have to maintain the byte so that it's available when you really want it, or else fseek back to the beginning, or else close and reopen.  All of these are legitimate workarounds but they're significantly more work than using stat or fstat.

So if I really needed to use FILE descriptors, I'd go with my open/fdopen strategy above.

Gary
A possible solution could be (starting from your code) :

FILE* ptr;
ptr = fopen("text.txt","r");

long Fo;    // File Offset

if (fseek(ptr,0,SEEK_END) == 0)
{
    Fo = ftell(ptr);
    if (Fo == 0)
    {
        // File is Empty ...
    }
    else
    {
        // File is NOT Empty ...
    }
}
else
{
    // Error ... !
}