954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how can i check for empty text file?

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.

missty
Newbie Poster
9 posts since Aug 2009
Reputation Points: 2
Solved Threads: 0
 

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";
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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;
	}
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

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

missty
Newbie Poster
9 posts since Aug 2009
Reputation Points: 2
Solved Threads: 0
 

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.

firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

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";
}
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You