I think it opens the file, gets the file length, allocates a buffer if the required size, then checks if any character elements is > 126, which is the upper limit of the text characters in the standard ascii chart.
So I would think this would work. Note: the following is untested and not compiled.
bool IsTextFile(string FileName)
{
bool isText = true;
// open the file in binary mode
ifstream in( FileName , ios::binary);
if( in.is_open() )
{
size_t len;
// locate end of file
in.seekg(0, ios::end);
// get file length
len = in.tellg();
// back to beginning of the file
in.seekg(0,ios::begin);
// allocate buffer space
unsigned char* buf = new [size+1];
// read the file into memory
in.read(static_cast<char*>(buf), size);
in.close();
// now check if its a text file
for(size_t i = 0; i < size && isTest == true; i++)
{
if( buf[i] < 13 || buf[i] > 126)
{
isText = false;
}
}
delete[] buf;
return isText;
}
There is another way to accomplish the same thing without allocating any memory. Just read the file one character at a time and test to see if it is a text character or not.
Last edited by Ancient Dragon; May 8th, 2008 at 11:02 pm.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Offline 21,953 posts
since Aug 2005