Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 195
  • Last Modified:

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
0
downatone
Asked:
downatone
  • 2
  • 2
1 Solution
 
GaryFxCommented:
Try using stat or fstat (at least on UNIX):

#include <sys/types.h>
#include <sys/stat.h>
...

struct stat buf;
int rc;
...
rc = stat("text.txt", &buf);
if (rc == 0 ) {
  if (buf.st_size == 0) {
     // File is empty
  }
}

Gary
0
 
downatoneAuthor Commented:
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
0
 
downatoneAuthor Commented:
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
0
 
GaryFxCommented:
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
0
 
marcdmCommented:
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 ... !
}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now