#pragma warning(disable: 4786)
#include <windows.h>
#include <vector>
//fast string class.
//We know the max size of the strings we're dealing with,
//we don't need the full std::string class
class fstring
{
private:
char buf[MAX_PATH];
public:
fstring(const char* const s)
{
strcpy(buf, s);
}
const char* const c_str() const
{
return buf;
}
void append(const char* const s)
{
strcat(buf, s);
}
} ;
//use a vector instead of a stack
//that we can use reserve() to pre-allocate the space for the stack
typedef std::vector<fstring> PathList;
typedef std::vector<fstring> FileList;
//--
inline void getFileList(const char* const aFileOrDirectory, FileList& filelist, bool& isfile)
{
isfile = false;
DWORD fattr = GetFileAttributes(aFileOrDirectory);
if (fattr == 0xFFFFFFFF)
{
printf("Could not find the file or directory '%s'\n", aFileOrDirectory);
return;
}
if ((fattr & FILE_ATTRIBUTE_DIRECTORY) == 0) //not a directory
{
isfile = true;
filelist.push_back(aFileOrDirectory);
return;
}
PathList dirs;
dirs.reserve(200);
WIN32_FIND_DATA fdata;
//start from the root directory and continue untill they're all gone
dirs.push_back(aFileOrDirectory);
while(!dirs.empty())
{
//get next directory
fstring dir(dirs.back());
dirs.pop_back();
fstring fspec(dir);
fspec.append("\\*.*");
HANDLE hfile = FindFirstFile(fspec.c_str(), &fdata);
if (hfile == INVALID_HANDLE_VALUE)
continue;
//for all the files in the directory
for (BOOL rc = TRUE; rc; rc = FindNextFile(hfile, &fdata))
{
if (strcmp(fdata.cFileName, ".") == 0 || strcmp(fdata.cFileName, "..") == 0)
continue;
fstring buf(dir);
buf.append("\\");
buf.append(strlwr(fdata.cFileName));
if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
dirs.push_back(buf);
else
filelist.push_back(buf);
}
FindClose(hfile);
}
}
//--
inline int GetType(const fstring& fname)
{
FILE* fp = fopen(fname.c_str(), "rb");
char buffer[4096];
int count = fread(buffer, 1, sizeof(buffer)-1, fp);
buffer[count] = 0;
int type = 0;
for (int i = 0; type == 0 && i < count; ++i)
{
//0x0D 0x0A
if (buffer[i] == 0x0D && buffer[i+1] == 0x0A)
type = 1;
else if (buffer[i] == 0x0A)
type = 2;
else if (buffer[i] == 0x09) //tab
;
else if (buffer[i] < ' ')
type = 3;
}
fclose(fp);
return type;
}
//--
inline void Print(const fstring& f, int type)
{
const char* p;
switch(type)
{
case 0: p = "???? "; break;
case 1: p = "DOS "; break;
case 2: p = "UNIX "; break;
case 3: p = "BIN "; break;
}
printf("%s %s\n", p, f.c_str());
}
//--
void usage()
{
printf("usage: jnewlines <file_or_directory>\n");
exit(1);
}
//--
int main(int argc, char** argv)
{
if (argc != 2)
{
usage();
return -1;
}
FileList flist;
flist.reserve(1000);
bool isfile;
getFileList(argv[1], flist, isfile);
if (isfile)
{
Print(argv[1], GetType(argv[1]));
}
else
{
for(FileList::iterator it = flist.begin(); it != flist.end(); ++it)
Print(*it, GetType(*it));
}
return 0;
}
|