can anyone tell me how can i create a function like:

if ("the txt file is blank")
dosomething;

which is checking if the text file is empty and then do something.

open the file, seek to end, get position, then finally check if position is 0.

ifstream in("myfile.txt");
in.seekp(0, ios::end);
int spot = in.tellg();
if( spot == 0)
{
    cout << "Empty file\n";
}

Damn Ancient Dragon beat me to it.

Anyhow here it is :

#include <iostream>
#include<fstream>

using namespace std;

int main()
{
	fstream oFile("numbers.txt");
	
	if(!oFile.is_open())
	{
		cout<<"Error opening the file\n";
		return 3;
	}

	oFile.seekg(0,std::ios::end);

	unsigned int size = oFile.tellg();

	if(!size)
		cout<<"Empty File\n";

	else 
	{
		char c;
		while(oFile.get(c))
			cout<<c;
	}
}

i think only ofstream can use seekp.
but i need to check that with ifstream.

For ifstream :

ifstream iFile("numbers.txt");
	
	if(!iFile.is_open())
	{
		cout<<"Error opening the file\n";
		return 3;
	}

	iFile.seekg(0,std::ios::end);
	unsigned int size = iFile.tellg();
	if(!size)
		cout<<"Empty File\n";

for ofstream,look at the prev post.

Another possibility?

#include <iostream>
#include <fstream>

int file_isempty(const char *filename)
{
   std::ifstream file(filename);
   return !file || file.get() == EOF;
}

int main()
{
   const char filename[] = "file.txt";
   std::cout << filename << (file_isempty(filename) ? " " : " non") << "empty\n";
}
This article has been dead for over six months. Start a new discussion instead.