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
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
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
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314