hari
hari

Reputation: 9733

FILE * can say if the file is empty?

In C, how do I know from FILE* whether that file is empty or not?

Upvotes: 1

Views: 7169

Answers (3)

Jim Balter
Jim Balter

Reputation: 16406

If you're coding for a POSIX system:

struct stat sb;
if( fstat(fileno(file), &sb) ) { /* error */ }
if( sb.st_size == 0 ) { /* file is empty */ }

Upvotes: 1

detunized
detunized

Reputation: 15289

Like this:

bool isEmpty(FILE *file)
{
    long savedOffset = ftell(file);
    fseek(file, 0, SEEK_END);

    if (ftell(file) == 0)
    {
        return true;
    }

    fseek(file, savedOffset, SEEK_SET);
    return false;
}

Upvotes: 5

Alexander Gessler
Alexander Gessler

Reputation: 46607

fseek to the end, then check if ftell returns 0.

Upvotes: 14

Related Questions