Could anyone please show me a working example of how to find if a file exists but is empty or not?

Thanks

Recommended Answers

All 9 Replies

Something using more standard c++:

#include <iostream>
#include <fstream>
...
ifstream myfile ("example.txt");
if(myfile.is_open())
{
long begin, end;
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
if(begin == end)
// empty
}
else
// didn't exist

thanks guys

Another way is to call _stat(), which will return the file size among other things.

The getline(fileName,line) also reads the last line that is an empty line. Is there any way not to read that last empty line?

No, but the program can ignore empry lines

int main()
{
    int count = 0;
    std::string line;
    std::ifstream in("textfile.txt");
    if(in.is_open())
    {
        while( getline(in, line) )
        {
            if( line.length() > 0)
            {
                cout << line << '\n';
                ++count;
            }
        }
    }
    cout << "# lines = " << count << '\n';
}

that's a good idea :)

if( line.length() > 0)

This is the code that the application is using to read the file and I have to modify it
1) do not read empty lines (especially the empty line at the end)
2) error when file does not exist
3) error when file does not open
4) error when file is empty

string pathFile = fpath + "/test.log"; 
     	ifstream f1;
     	f1.open(pathFile.c_str());

     	if(f1.fail()) 
	{
        	LOG("Failed to open test.log file");
     	}
     	else 
	{
            while(getline(f1,line)) // reading line by line
		{
                                // do something
                 }

                 f1.close();  
       }

when I delete the file i-e make it non-existent then it shows the following error

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr
Aborted (core dumped)

I am sorry. It is the other way around. When I put the file back into the directory after modifying the code for all these exception and then run the code, it shows the error std::out_of_range

;'(

>>if(f1.fail())
That should be if( !f1.is_open() ) to check if the file was opened or not. I've also seen if( !f1 )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.