Checking if binary file is empty

So I've been coding a program that uses a binary file. In the program though, I want it to check if the file is empty. I've been searching, and found a solution that seemed promising, however, I'm getting an error "more than one operator "==" matches these operands." Here is my pseudo code:

1
2
3
4
5
fstream inFile("file.dat" | ios_base::in | ios_base::out | ios::base::binary);
inFile.seekg(0, ios_base::end);
if(inFile.tellg() == 0){
//File is empty
}


Error is with the equal to operator. Thanks for any help!
Last edited on
1
2
3
4
5
fstream inFile("file.dat", ios_base::in | ios_base::out | ios::base::binary);
inFile.seekg(0, ios_base::end);
if(inFile.tellg() == 0){
//File is empty
}
1
2
3
4
5
6
7
std::ifstream file( "whatever", std::ios::binary ) ;

if( !file )
      std::cerr << "couldn't open file\n" ;

else if( file.tellg() == std::ifstream::traits_type::eof() )
      std::cout << "the file is empty\n" ;

To shadow123, that's what I typed down...... and as I said, if you would have read my post, it does not work because it produces an error (which I have typed what that error is)

To JLBorges, I'm still getting the same error as my first one.

To kbw, I suppose I'll try it out, but upon looking at it, I don't really understand it too well. I'll just see if I can find other sites that explains it better
1
2
3
4
5
	std::fstream inFile("file.dat", std::ios::in | std::ios::out | std::ios::binary);
	inFile.seekg(0, std::ios::end);
	if(inFile.tellg() == static_cast<std::streamoff>(0)){
	//File is empty
	}
I don't really understand it too well.
Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <sys/stat.h>

int main()
{
    struct stat info;
    int ret = stat("file.dat", &info);
    if (ret == -1)
    {
        std::cout << "File does not exist" << std::endl;
        return 1;
    }

    std::cout << "File size is: " << info.st_size << " bytes" << std::endl;
    return 0;
}

The idea is, opening a file is one of the most expensive things you can do locally on a computer. stat() checks the metadata for the file and so doesn't update the file or metadata (last access time for example), and so is faster, simpler, more efficient and has no side effects.

Please don't open a file just to check it's size or existence.
> To JLBorges, I'm still getting the same error as my first one.

My mistake. Should have been:

1
2
3
4
5
6
7
std::ifstream file( "whatever", std::ios::binary ) ;

if( !file )
      std::cerr << "couldn't open file\n" ;

else if( file.peek() /*tellg()*/ == std::ifstream::traits_type::eof() )
      std::cout << "the file is empty\n" ;
Topic archived. No new replies allowed.