How do I check if a binary file is empty?

Dec 5, 2011 at 10:12pm
How do I check if a binary file is empty? i tried searching for it but nothing came up of use.
Dec 5, 2011 at 10:17pm
If it is of size zero, it's empty. If it is even a single byte in size, it isn't.
Dec 5, 2011 at 10:23pm
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>
#include <iostream>

int main()
{
	std::ifstream file("filename", std::ios::binary);
        
	file.seekg(0, std::ios::end);
	if (file.tellg() == 0)
	{
		std::cout << "File is empty" << std::endl;
	}
}
Dec 5, 2011 at 10:30pm
Getting this error:

ambiguous overload for 'operator==' in '((std::basic_istream<char, std::char_traits<char> >*)(+myfile))->std::basic_istream<_CharT, _Traits>::tellg [with _CharT = char, _Traits = std::char_traits<char>]() == 0'
Dec 5, 2011 at 10:38pm
If you would rather use the old C standard then you could do this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstdio>// Used for the file handling
using namespace std;// We want to specify the standard namespace

// The start of the sample program
int main() {// Look up
    // Change the file to the one you want to read
    FILE* NewFile = fopen("Text.dat","rb");// Open the file for reading in binary mode
    if((NewFile != NULL) ||// If we could not open the file
       (fgetc(NewFile) == EOF)) {// Or if the file realy is empty
            fclose(NewFile);// Close the file
            return 0;// Close the program
    } else {// If the file is not empty
        fseek(NewFile,-1,SEEK_CUR);// Unread that character
        // Do what ever else you want to do with that file
    }// End of If statement
}// End of main(void)
Dec 5, 2011 at 11:08pm
There must be an error on my part somewhere. The help is very much appreciated though, thanks!
going to mark as solved
Topic archived. No new replies allowed.