Check whether a file is empty.

codephantom me at noyb.com
Sat Dec 9 03:17:30 UTC 2017


On Friday, 8 December 2017 at 19:13:20 UTC, vino wrote:
> Hi,
>
>  The code is same just copy pasted the code form Windows 7 into 
> Windows 2003 and executed, in Windows 7 the log file is of size 
> 0 where as in windows 2003 the log file is of size 2 byte where 
> the log file in both the server is empty.
>
> From,
> Vino.B

It certainly sounds like some kind of encoding issue.

I guess you don't have much choice other than to read the 
contents of the file, and determine what it actually contains.

Assuming these log files of yours are 'ascii text' files, then if 
the file is less than say .. 5 bytes.. you could check if it 
*only* contained *non-printable* characters, in which case it's 
'likely' an empty file.

something very silly, like this, might do it ;-)

// -------

bool isFileLikelyEmpty(string filename)
{

     import std.exception, std.file, std.ascii, std.conv;

     File f = filename;

     enforce(f.size < 5,
         "This file is not likely to be empty." ~
         " No point in continuing."); // 5 seems reasonable cutoff 
;-)

     bool result = false;
     int charCount = 0;
     auto str = readText(filename);

     foreach(c; str)
     {
         // https://dlang.org/phobos/std_ascii.html#isPrintable
         if( !isPrintable(c) )
             charCount++;
     }

     if(charCount == str.length)
         result = true; // file is likely empty, as all characters 
are non-printable.

     return result;
}

// ---------



More information about the Digitalmars-d-learn mailing list