Merge pull request #2020 from vgturtle127/beautification-5

Beautification 5 - Source/Common directory
This commit is contained in:
zilmar 2021-03-18 13:00:15 +10:30 committed by GitHub
commit 77a3080b63
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 476 additions and 543 deletions

View File

@ -29,12 +29,13 @@ CriticalSection::~CriticalSection(void)
#endif #endif
} }
/** /*
* Enters a critical section of code. Enters a critical section of code.
* Prevents other threads from accessing the section between the enter and leave sections simultaneously. Prevents other threads from accessing the section between the enter and leave sections simultaneously.
* @note It is good practice to try and keep the critical section code as little as possible, so that Note: It is good practice to try and keep the critical section code as little as possible, so that
* other threads are not locked waiting for it. other threads are not locked waiting for it.
*/ */
void CriticalSection::enter(void) void CriticalSection::enter(void)
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -44,13 +45,14 @@ void CriticalSection::enter(void)
#endif #endif
} }
/** /*
* Leaves the critical section. Leaves the critical section.
* Allows threads access to the critical code section again. Allows threads access to the critical code section again.
* @warning Note that an exception occurring with a critical section may not result in the expected leave being Warning: Note that an exception occurring with a critical section may not result in the expected leave being
* called. To ensure that your critical section is exception safe, ensure that you wrap the critical called. To ensure that your critical section is exception safe, ensure that you wrap the critical
* section in a try catch, and the catch calls the leave method. section in a try catch, and the catch calls the leave method.
*/ */
void CriticalSection::leave(void) void CriticalSection::leave(void)
{ {
#ifdef _WIN32 #ifdef _WIN32

View File

@ -31,4 +31,3 @@ private:
CGuard(const CGuard& copy); CGuard(const CGuard& copy);
CGuard &operator=(const CGuard& rhs); CGuard &operator=(const CGuard& rhs);
}; };

View File

@ -88,7 +88,7 @@ bool CFile::Open(const char * lpszFileName, uint32_t nOpenFlags)
_ASSERTE(false); _ASSERTE(false);
} }
// map share mode // Map share mode
ULONG dwShareMode = 0; ULONG dwShareMode = 0;
dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
@ -96,20 +96,20 @@ bool CFile::Open(const char * lpszFileName, uint32_t nOpenFlags)
if ((nOpenFlags & shareDenyRead) == shareDenyRead) { dwShareMode &= ~FILE_SHARE_READ; } if ((nOpenFlags & shareDenyRead) == shareDenyRead) { dwShareMode &= ~FILE_SHARE_READ; }
if ((nOpenFlags & shareExclusive) == shareExclusive) { dwShareMode = 0; } if ((nOpenFlags & shareExclusive) == shareExclusive) { dwShareMode = 0; }
// map modeNoInherit flag // Map modeNoInherit flag
SECURITY_ATTRIBUTES sa; SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa); sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL; sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = (nOpenFlags & modeNoInherit) == 0; sa.bInheritHandle = (nOpenFlags & modeNoInherit) == 0;
// map creation flags // Map creation flags
ULONG dwCreateFlag = OPEN_EXISTING; ULONG dwCreateFlag = OPEN_EXISTING;
if (nOpenFlags & modeCreate) if (nOpenFlags & modeCreate)
{ {
dwCreateFlag = ((nOpenFlags & modeNoTruncate) != 0) ? OPEN_ALWAYS : CREATE_ALWAYS; dwCreateFlag = ((nOpenFlags & modeNoTruncate) != 0) ? OPEN_ALWAYS : CREATE_ALWAYS;
} }
// attempt file creation // Attempt file creation
HANDLE hFile = ::CreateFileA(lpszFileName, dwAccess, dwShareMode, &sa, dwCreateFlag, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE hFile = ::CreateFileA(lpszFileName, dwAccess, dwShareMode, &sa, dwCreateFlag, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) if (hFile == INVALID_HANDLE_VALUE)
{ //#define ERROR_PATH_NOT_FOUND 3L { //#define ERROR_PATH_NOT_FOUND 3L
@ -232,7 +232,7 @@ bool CFile::Write(const void* lpBuf, uint32_t nCount)
{ {
if (nCount == 0) if (nCount == 0)
{ {
return true; // avoid Win32 "null-write" option return true; // Avoid Win32 "null-write" option
} }
#ifdef USE_WINDOWS_API #ifdef USE_WINDOWS_API
@ -260,7 +260,7 @@ uint32_t CFile::Read(void* lpBuf, uint32_t nCount)
{ {
if (nCount == 0) if (nCount == 0)
{ {
return 0; // avoid Win32 "null-read" return 0; // Avoid Win32 "null-read"
} }
#ifdef USE_WINDOWS_API #ifdef USE_WINDOWS_API

View File

@ -61,7 +61,7 @@ public:
uint32_t SeekToEnd ( void ); uint32_t SeekToEnd ( void );
void SeekToBegin ( void ); void SeekToBegin ( void );
// Overridables // Overridable
virtual uint32_t GetPosition() const; virtual uint32_t GetPosition() const;
virtual int32_t Seek(int32_t lOff, SeekPosition nFrom); virtual int32_t Seek(int32_t lOff, SeekPosition nFrom);
virtual bool SetLength(uint32_t dwNewLen); virtual bool SetLength(uint32_t dwNewLen);

View File

@ -119,7 +119,7 @@ int CIniFileBase::GetStringFromFile(char * & String, std::unique_ptr<char> &Data
} }
else else
{ {
//Increase buffer size // Increase buffer size
int NewMaxDataSize = MaxDataSize + BufferIncrease; int NewMaxDataSize = MaxDataSize + BufferIncrease;
char * NewBuffer = new char[NewMaxDataSize]; char * NewBuffer = new char[NewMaxDataSize];
if (NewBuffer == NULL) if (NewBuffer == NULL)
@ -165,7 +165,7 @@ void CIniFileBase::SaveCurrentSection(void)
if (m_CurrentSectionFilePos == -1) if (m_CurrentSectionFilePos == -1)
{ {
//Section has not been added yet // Section has not been added yet
m_File.Seek(0, CFileBase::end); m_File.Seek(0, CFileBase::end);
int len = (int)m_CurrentSection.length() + (lineFeedLen * 2) + 5; int len = (int)m_CurrentSection.length() + (lineFeedLen * 2) + 5;
@ -184,7 +184,7 @@ void CIniFileBase::SaveCurrentSection(void)
} }
else else
{ {
//increase/decrease space needed // Increase/decrease space needed
int NeededBufferLen = 0; int NeededBufferLen = 0;
{ {
std::unique_ptr<char> LineData; std::unique_ptr<char> LineData;
@ -210,7 +210,7 @@ void CIniFileBase::SaveCurrentSection(void)
std::unique_ptr<char> Data; std::unique_ptr<char> Data;
char *Input = NULL; char *Input = NULL;
//Skip first line as it is the section name // Skip first line as it is the section name
int StartPos = m_CurrentSectionFilePos; int StartPos = m_CurrentSectionFilePos;
int EndPos = StartPos; int EndPos = StartPos;
do do
@ -237,7 +237,7 @@ void CIniFileBase::SaveCurrentSection(void)
m_File.Flush(); m_File.Flush();
ClearSectionPosList(StartPos); ClearSectionPosList(StartPos);
} }
//set pointer to beginning of the start pos // Set pointer to beginning of the start POS
m_File.Seek(StartPos, CFileBase::begin); m_File.Seek(StartPos, CFileBase::begin);
} }
@ -328,7 +328,7 @@ bool CIniFileBase::MoveToSectionNameData(const char * lpSectionName, bool Change
if (result <= 1) { continue; } if (result <= 1) { continue; }
if (strlen(CleanLine(Input)) <= 1) { continue; } if (strlen(CleanLine(Input)) <= 1) { continue; }
//We Only care about sections // We only care about sections
char * CurrentSection = Input; char * CurrentSection = Input;
if (m_lastSectionSearch == 0 && !memcmp(CurrentSection, pUTF8, 3)) if (m_lastSectionSearch == 0 && !memcmp(CurrentSection, pUTF8, 3))
@ -339,7 +339,7 @@ bool CIniFileBase::MoveToSectionNameData(const char * lpSectionName, bool Change
if (CurrentSection[0] != '[') { continue; } if (CurrentSection[0] != '[') { continue; }
int lineEndPos = (int)strlen(CurrentSection) - 1; int lineEndPos = (int)strlen(CurrentSection) - 1;
if (CurrentSection[lineEndPos] != ']') { continue; } if (CurrentSection[lineEndPos] != ']') { continue; }
//take off the ']' from the end of the string // Take off the ']' from the end of the string
CurrentSection[lineEndPos] = 0; CurrentSection[lineEndPos] = 0;
CurrentSection += 1; CurrentSection += 1;
m_lastSectionSearch = (m_File.GetPosition() - DataSize) + ReadPos; m_lastSectionSearch = (m_File.GetPosition() - DataSize) + ReadPos;
@ -407,7 +407,7 @@ const char * CIniFileBase::CleanLine(char * Line)
{ {
char * Pos = Line; char * Pos = Line;
//Remove any comment from the line // Remove any comment from the line
while (Pos != NULL) while (Pos != NULL)
{ {
Pos = strchr(Pos, '/'); Pos = strchr(Pos, '/');
@ -438,7 +438,7 @@ const char * CIniFileBase::CleanLine(char * Line)
} }
} }
//strip any spaces or line feeds from the end of the line // Strip any spaces or line feeds from the end of the line
for (int count = (int)strlen(&Line[0]) - 1; count >= 0; count--) for (int count = (int)strlen(&Line[0]) - 1; count >= 0; count--)
{ {
if (Line[count] != ' ' && Line[count] != '\r') { break; } if (Line[count] != ' ' && Line[count] != '\r') { break; }
@ -458,7 +458,7 @@ void CIniFileBase::OpenIniFileReadOnly()
void CIniFileBase::OpenIniFile(bool bCreate) void CIniFileBase::OpenIniFile(bool bCreate)
{ {
//Open for reading/Writing // Open for reading/writing
m_ReadOnly = false; m_ReadOnly = false;
if (!m_File.Open(m_FileName.c_str(), CFileBase::modeReadWrite | CFileBase::shareDenyWrite)) if (!m_File.Open(m_FileName.c_str(), CFileBase::modeReadWrite | CFileBase::shareDenyWrite))
{ {
@ -721,7 +721,7 @@ void CIniFileBase::SaveString(const char * lpSectionName, const char * lpKeyNam
void CIniFileBase::SaveNumber(const char * lpSectionName, const char * lpKeyName, int32_t Value) void CIniFileBase::SaveNumber(const char * lpSectionName, const char * lpKeyName, int32_t Value)
{ {
//translate the string to an ascii version and save as text // Translate the string to an ASCII version and save as text
SaveString(lpSectionName, lpKeyName, FormatStr("%d", Value).c_str()); SaveString(lpSectionName, lpKeyName, FormatStr("%d", Value).c_str());
} }

View File

@ -73,10 +73,10 @@ private:
std::string m_CurrentSection; std::string m_CurrentSection;
bool m_CurrentSectionDirty; bool m_CurrentSectionDirty;
int m_CurrentSectionFilePos; // Where in the file is the current Section int m_CurrentSectionFilePos; // Where in the file is the current section
KeyValueList m_CurrentSectionData; KeyValueList m_CurrentSectionData;
long m_lastSectionSearch; // When Scanning for a section, what was the last scanned pos long m_lastSectionSearch; // When scanning for a section, what was the last scanned POS
bool m_ReadOnly; bool m_ReadOnly;
bool m_InstantFlush; bool m_InstantFlush;
@ -102,7 +102,7 @@ public:
CIniFileT(const char * FileName) : CIniFileT(const char * FileName) :
CIniFileBase(m_FileObject, FileName) CIniFileBase(m_FileObject, FileName)
{ {
//Try to open file for reading // Try to open file for reading
OpenIniFile(); OpenIniFile();
} }
@ -115,7 +115,7 @@ public:
} }
else else
{ {
//Try to open file for reading // Try to open file for reading
OpenIniFile(bCreate); OpenIniFile(bCreate);
} }
} }

View File

@ -92,9 +92,9 @@ void CLog::Log( const char * Message )
m_FileSize += message_len; m_FileSize += message_len;
if (m_TruncateFileLog && m_FileSize > m_MaxFileSize) if (m_TruncateFileLog && m_FileSize > m_MaxFileSize)
{ {
// check file size // Check file size
m_FileSize = m_hLogFile.GetLength(); m_FileSize = m_hLogFile.GetLength();
// if larger then max size then // If larger then maximum size then
if (m_FileSize > m_MaxFileSize) if (m_FileSize > m_MaxFileSize)
{ {
if (!m_FlushOnWrite) if (!m_FlushOnWrite)
@ -105,7 +105,7 @@ void CLog::Log( const char * Message )
uint32_t end = m_hLogFile.SeekToEnd(); uint32_t end = m_hLogFile.SeekToEnd();
// move to reduce size // Move to reduce size
m_hLogFile.Seek((end - m_MaxFileSize) + m_FileChangeSize,CFile::begin); m_hLogFile.Seek((end - m_MaxFileSize) + m_FileChangeSize,CFile::begin);
// Find next end of line // Find next end of line
@ -131,7 +131,7 @@ void CLog::Log( const char * Message )
NextEnter += dwRead; NextEnter += dwRead;
} while(dwRead != 0); } while(dwRead != 0);
// copy content of log to the new file // Copy content of log to the new file
uint32_t ReadPos = (end - m_MaxFileSize) + m_FileChangeSize + NextEnter; uint32_t ReadPos = (end - m_MaxFileSize) + m_FileChangeSize + NextEnter;
uint32_t SizeToRead, WritePos = 0; uint32_t SizeToRead, WritePos = 0;
do do
@ -158,7 +158,7 @@ void CLog::Log( const char * Message )
WritePos += dwRead; WritePos += dwRead;
} while (SizeToRead > 0); } while (SizeToRead > 0);
//clean up // Clean up
m_hLogFile.SetEndOfFile(); m_hLogFile.SetEndOfFile();
m_hLogFile.Flush(); m_hLogFile.Flush();
m_FileSize = m_hLogFile.GetLength(); m_FileSize = m_hLogFile.GetLength();

View File

@ -66,7 +66,7 @@ void* AllocateAddressSpace(size_t size, void * base_address)
bool FreeAddressSpace(void* addr, size_t size) bool FreeAddressSpace(void* addr, size_t size)
{ {
#ifdef _WIN32 #ifdef _WIN32
size = 0; //unused size = 0; // Unused
return VirtualFree(addr, 0, MEM_RELEASE) != 0; return VirtualFree(addr, 0, MEM_RELEASE) != 0;
#else #else
msync(addr, size, MS_SYNC); msync(addr, size, MS_SYNC);
@ -96,7 +96,7 @@ bool DecommitMemory(void* addr, size_t size)
#ifdef _WIN32 #ifdef _WIN32
return VirtualFree((void*)addr, size, MEM_DECOMMIT) != 0; return VirtualFree((void*)addr, size, MEM_DECOMMIT) != 0;
#else #else
// instead of unmapping the address, we're just gonna trick // Instead of unmapping the address, we're just gonna trick
// the TLB to mark this as a new mapped area which, due to // the TLB to mark this as a new mapped area which, due to
// demand paging, will not be committed until used. // demand paging, will not be committed until used.

View File

@ -14,7 +14,7 @@ int _vscprintf (const char * format, va_list pargs);
#endif #endif
//FPU rounding code // FPU rounding code
#ifdef _WIN32 #ifdef _WIN32
typedef enum { FE_TONEAREST = 0, FE_TOWARDZERO, FE_UPWARD, FE_DOWNWARD } eRoundType; typedef enum { FE_TONEAREST = 0, FE_TOWARDZERO, FE_UPWARD, FE_DOWNWARD } eRoundType;
int fesetround(int RoundType); int fesetround(int RoundType);

View File

@ -1,9 +1,5 @@
/* // Implements the CRandom class
* Implements the CRandom class. // This class implements the Lehmer Random Number Generator
*
* This class implements the Lehmer Random Number Generator.
*
*/
#include "stdafx.h" #include "stdafx.h"
#include "Random.h" #include "Random.h"

View File

@ -1,9 +1,6 @@
/* // Defines the CRandom class
* Defines the CRandom class. // This class implements the Lehmer Random Number Generator
*
* This class implements the Lehmer Random Number Generator.
*
*/
#pragma once #pragma once
#include <Common/stdtypes.h> #include <Common/stdtypes.h>

View File

@ -1,12 +1,12 @@
#pragma once #pragma once
//The template class definition for smart pointer // The template class definition for smart pointer
template<class _Ty> template<class _Ty>
class AUTO_PTR class AUTO_PTR
{ {
public: public:
typedef _Ty element_type; typedef _Ty element_type;
//ctor // CTOR
explicit AUTO_PTR(_Ty *pVal = 0) throw() : explicit AUTO_PTR(_Ty *pVal = 0) throw() :
m_Owns(pVal != 0), m_Owns(pVal != 0),
m_AutoPtr(pVal) m_AutoPtr(pVal)
@ -14,14 +14,14 @@ public:
{ {
} }
//copy ctor // Copy CTOR
AUTO_PTR(const AUTO_PTR<_Ty>& ptrCopy) throw() : AUTO_PTR(const AUTO_PTR<_Ty>& ptrCopy) throw() :
m_Owns(ptrCopy.m_Owns), m_Owns(ptrCopy.m_Owns),
m_AutoPtr(ptrCopy.release()) m_AutoPtr(ptrCopy.release())
{ {
} }
//overloading = operator // Overloading = operator
AUTO_PTR<_Ty>& operator=(AUTO_PTR<_Ty>& ptrCopy) throw() AUTO_PTR<_Ty>& operator=(AUTO_PTR<_Ty>& ptrCopy) throw()
{ {
if (this != &ptrCopy) if (this != &ptrCopy)
@ -42,7 +42,7 @@ public:
} }
return (*this); return (*this);
} }
//dtor // DTOR
~AUTO_PTR() ~AUTO_PTR()
{ {
if (m_Owns) if (m_Owns)
@ -50,25 +50,25 @@ public:
delete m_AutoPtr; delete m_AutoPtr;
} }
} }
//overloading * operator // Overloading * operator
_Ty& operator*() const throw() _Ty& operator*() const throw()
{ {
return (*get()); return (*get());
} }
//overloading -> operator // Overloading -> operator
_Ty *operator->() const throw() _Ty *operator->() const throw()
{ {
return (get()); return (get());
} }
//function to get the pointer to the class // Function to get the pointer to the class
_Ty *get() const throw() _Ty *get() const throw()
{ {
return (m_AutoPtr); return (m_AutoPtr);
} }
//function to get the pointer to the class and take ownership // Function to get the pointer to the class and take ownership
_Ty *release() const throw() _Ty *release() const throw()
{ {
((AUTO_PTR<_Ty> *)this)->m_Owns = false; ((AUTO_PTR<_Ty> *)this)->m_Owns = false;

View File

@ -145,7 +145,7 @@ stdstr & stdstr::TrimLeft(const char * chars2remove)
} }
else else
{ {
erase(begin(), end()); // make empty erase(begin(), end()); // Make empty
} }
} }
return *this; return *this;
@ -162,7 +162,7 @@ stdstr & stdstr::TrimRight(const char * chars2remove)
} }
else else
{ {
erase(begin(), end()); // make empty erase(begin(), end()); // Make empty
} }
} }
return *this; return *this;
@ -179,7 +179,7 @@ stdstr & stdstr::Trim(const char * chars2remove)
} }
else else
{ {
erase(begin(), end()); // make empty erase(begin(), end()); // Make empty
} }
pos = find_last_not_of(chars2remove); pos = find_last_not_of(chars2remove);
@ -189,7 +189,7 @@ stdstr & stdstr::Trim(const char * chars2remove)
} }
else else
{ {
erase(begin(), end()); // make empty erase(begin(), end()); // Make empty
} }
} }
return *this; return *this;

View File

@ -26,7 +26,7 @@ CThread::~CThread()
WriteTrace(TraceThread, TraceDebug, "Start"); WriteTrace(TraceThread, TraceDebug, "Start");
if (CThread::GetCurrentThreadId() == m_threadID) if (CThread::GetCurrentThreadId() == m_threadID)
{ {
WriteTrace(TraceThread, TraceError, "Deleting from thread!!!"); WriteTrace(TraceThread, TraceError, "Deleting from thread!");
} }
if (CThread::GetCurrentThreadId() != m_threadID && isRunning()) if (CThread::GetCurrentThreadId() != m_threadID && isRunning())
{ {

View File

@ -1,43 +1,43 @@
// MD5.CC - source code for the C++/object oriented translation and /*
// modification of MD5.
// Translation and modification (c) 1995 by Mordechai T. Abzug MD5.CC - source code for the C++/object oriented translation and modification of MD5.
// This translation/ modification is provided "as is," without express or Translation and modification (c) 1995 by Mordechai T. Abzug
// implied warranty of any kind.
// The translator/ modifier does not claim (1) that MD5 will do what you think This translation/ modification is provided "as is," without express or
// it does; (2) that this translation/ modification is accurate; or (3) that implied warranty of any kind.
// this software is "merchantible." (Language for this disclaimer partially
// copied from the disclaimer below).
/* based on: The translator/ modifier does not claim (1) that MD5 will do what you think
it does; (2) that this translation/ modification is accurate; or (3) that
this software is "merchantable." (Language for this disclaimer partially
copied from the disclaimer below).
MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm based on:
MDDRIVER.C - test driver for MD2, MD4 and MD5
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All MD5.H - header file for MD5C.C
rights reserved. MDDRIVER.C - test driver for MD2, MD4 and MD5
License to copy and use this software is granted provided that it Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided License to copy and use this software is granted provided that it
that such works are identified as "derived from the RSA Data is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Security, Inc. MD5 Message-Digest Algorithm" in all material Algorithm" in all material mentioning or referencing this software
mentioning or referencing the derived work. or this function.
RSA Data Security, Inc. makes no representations concerning either License is also granted to make and use derivative works provided
the merchantability of this software or the suitability of this that such works are identified as "derived from the RSA Data
software for any particular purpose. It is provided "as is" Security, Inc. MD5 Message-Digest Algorithm" in all material
without express or implied warranty of any kind. mentioning or referencing the derived work.
These notices must be retained in any copies of any part of this RSA Data Security, Inc. makes no representations concerning either
documentation and/or software. the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
*/ These notices must be retained in any copies of any part of this
documentation and/or software.
*/
#include "stdafx.h" #include "stdafx.h"
@ -54,12 +54,13 @@ MD5::~MD5()
// MD5 block update operation. Continues an MD5 message-digest // MD5 block update operation. Continues an MD5 message-digest
// operation, processing another message block, and updating the // operation, processing another message block, and updating the
// context. // context.
void MD5::update(const uint1 *input, uint4 input_length) void MD5::update(const uint1 *input, uint4 input_length)
{ {
uint4 input_index, buffer_index; uint4 input_index, buffer_index;
uint4 buffer_space; // how much space is left in buffer uint4 buffer_space; // How much space is left in the buffer
if (finalized) // so we can't update! if (finalized) // So we can't update!
{ {
WriteTrace(TraceMD5, TraceError, "Can't update a finalized digest!"); WriteTrace(TraceMD5, TraceError, "Can't update a finalized digest!");
return; return;
@ -76,34 +77,34 @@ void MD5::update(const uint1 *input, uint4 input_length)
count[1] += ((uint4)input_length >> 29); count[1] += ((uint4)input_length >> 29);
buffer_space = 64 - buffer_index; // how much space is left in buffer buffer_space = 64 - buffer_index; // How much space is left in the buffer
// Transform as many times as possible. // Transform as many times as possible
if (input_length >= buffer_space) // ie. we have enough to fill the buffer if (input_length >= buffer_space) // i.e. we have enough to fill the buffer
{ {
// fill the rest of the buffer and transform // Fill the rest of the buffer and transform
memcpy(buffer + buffer_index, (unsigned char *)input, buffer_space); memcpy(buffer + buffer_index, (unsigned char *)input, buffer_space);
transform(buffer); transform(buffer);
// now, transform each 64-byte piece of the input, bypassing the buffer // Now, transform each 64-byte piece of the input, bypassing the buffer
for (input_index = buffer_space; input_index + 63 < input_length; input_index += 64) for (input_index = buffer_space; input_index + 63 < input_length; input_index += 64)
{ {
transform((unsigned char *)(input + input_index)); transform((unsigned char *)(input + input_index));
} }
buffer_index = 0; // so we can buffer remaining buffer_index = 0; // So we can buffer remaining
} }
else else
{ {
input_index = 0; // so we can buffer the whole input input_index = 0; // So we can buffer the whole input
} }
// and here we do the buffering: // Here we do the buffering:
memcpy(buffer + buffer_index, (unsigned char *)(input + input_index), input_length - input_index); memcpy(buffer + buffer_index, (unsigned char *)(input + input_index), input_length - input_index);
} }
// MD5 update for files. // MD5 update for files
// Like above, except that it works on files (and uses above as a primitive.) // Like above, except that it works on files (and uses above as a primitive)
void MD5::update(FILE *file) void MD5::update(FILE *file)
{ {
@ -123,7 +124,7 @@ void MD5::update(FILE *file)
} }
// MD5 finalization. Ends an MD5 message-digest operation, writing the // MD5 finalization. Ends an MD5 message-digest operation, writing the
// the message digest and zeroizing the context. // the message digest and zeroing the context
void MD5::finalize() void MD5::finalize()
{ {
@ -145,7 +146,7 @@ void MD5::finalize()
// Save number of bits // Save number of bits
encode(bits, count, 8); encode(bits, count, 8);
// Pad out to 56 mod 64. // Pad out to 56 mod 64
index = (uint4)((count[0] >> 3) & 0x3f); index = (uint4)((count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index); padLen = (index < 56) ? (56 - index) : (120 - index);
update(PADDING, padLen); update(PADDING, padLen);
@ -164,7 +165,7 @@ void MD5::finalize()
MD5::MD5(CPath File) MD5::MD5(CPath File)
{ {
init(); // must be called be all constructors init(); // Must be called by all constructors
if (File.Exists()) if (File.Exists())
{ {
FILE * fp = fopen((const char *)File, "rb"); FILE * fp = fopen((const char *)File, "rb");
@ -178,21 +179,21 @@ MD5::MD5(CPath File)
MD5::MD5(FILE *file) MD5::MD5(FILE *file)
{ {
init(); // must be called be all constructors init(); // Must be called by all constructors
update(file); update(file);
finalize(); finalize();
} }
MD5::MD5(const unsigned char *input, unsigned int input_length) MD5::MD5(const unsigned char *input, unsigned int input_length)
{ {
init(); // must called by all constructors init(); // Must be called by all constructors
update(input, input_length); update(input, input_length);
finalize(); finalize();
} }
MD5::MD5(const stdstr & string) MD5::MD5(const stdstr & string)
{ {
init(); // must called by all constructors init(); // Must be called by all constructors
update((const unsigned char *)string.c_str(), string.length()); update((const unsigned char *)string.c_str(), string.length());
finalize(); finalize();
} }
@ -245,15 +246,16 @@ const char *MD5::hex_digest()
} }
// PRIVATE METHODS: // PRIVATE METHODS:
void MD5::init() void MD5::init()
{ {
finalized = 0; // we just started! finalized = 0; // We just started!
// Nothing counted, so count=0 // Nothing counted, so count=0
count[0] = 0; count[0] = 0;
count[1] = 0; count[1] = 0;
// Load magic initialization constants. // Load magic initialization constants
state[0] = 0x67452301; state[0] = 0x67452301;
state[1] = 0xefcdab89; state[1] = 0xefcdab89;
state[2] = 0x98badcfe; state[2] = 0x98badcfe;
@ -287,97 +289,99 @@ void MD5::init()
#define S44 21 #define S44 21
// MD5 basic transformation. Transforms state based on block. // MD5 basic transformation. Transforms state based on block.
void MD5::transform(uint1 block[64]) void MD5::transform(uint1 block[64])
{ {
uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode(x, block, 64); decode(x, block, 64);
//ATLASSERT(!finalized); // not just a user error, since the method is private //ATLASSERT(!finalized); // Not just a user error, since the method is private
/* Round 1 */ // Round 1
FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ FF(a, b, c, d, x[0], S11, 0xd76aa478); // 1
FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ FF(d, a, b, c, x[1], S12, 0xe8c7b756); // 2
FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ FF(c, d, a, b, x[2], S13, 0x242070db); // 3
FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ FF(b, c, d, a, x[3], S14, 0xc1bdceee); // 4
FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ FF(a, b, c, d, x[4], S11, 0xf57c0faf); // 5
FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ FF(d, a, b, c, x[5], S12, 0x4787c62a); // 6
FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ FF(c, d, a, b, x[6], S13, 0xa8304613); // 7
FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ FF(b, c, d, a, x[7], S14, 0xfd469501); // 8
FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ FF(a, b, c, d, x[8], S11, 0x698098d8); // 9
FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ FF(d, a, b, c, x[9], S12, 0x8b44f7af); // 10
FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF(c, d, a, b, x[10], S13, 0xffff5bb1); // 11
FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF(b, c, d, a, x[11], S14, 0x895cd7be); // 12
FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF(a, b, c, d, x[12], S11, 0x6b901122); // 13
FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF(d, a, b, c, x[13], S12, 0xfd987193); // 14
FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF(c, d, a, b, x[14], S13, 0xa679438e); // 15
FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ FF(b, c, d, a, x[15], S14, 0x49b40821); // 16
/* Round 2 */ // Round 2
GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ GG(a, b, c, d, x[1], S21, 0xf61e2562); // 17
GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ GG(d, a, b, c, x[6], S22, 0xc040b340); // 18
GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG(c, d, a, b, x[11], S23, 0x265e5a51); // 19
GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); // 20
GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ GG(a, b, c, d, x[5], S21, 0xd62f105d); // 21
GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG(d, a, b, c, x[10], S22, 0x2441453); // 22
GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG(c, d, a, b, x[15], S23, 0xd8a1e681); // 23
GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); // 24
GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ GG(a, b, c, d, x[9], S21, 0x21e1cde6); // 25
GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG(d, a, b, c, x[14], S22, 0xc33707d6); // 26
GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ GG(c, d, a, b, x[3], S23, 0xf4d50d87); // 27
GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ GG(b, c, d, a, x[8], S24, 0x455a14ed); // 28
GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG(a, b, c, d, x[13], S21, 0xa9e3e905); // 29
GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ GG(d, a, b, c, x[2], S22, 0xfcefa3f8); // 30
GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ GG(c, d, a, b, x[7], S23, 0x676f02d9); // 31
GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); // 32
/* Round 3 */ // Round 3
HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ HH(a, b, c, d, x[5], S31, 0xfffa3942); // 33
HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ HH(d, a, b, c, x[8], S32, 0x8771f681); // 34
HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH(c, d, a, b, x[11], S33, 0x6d9d6122); // 35
HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH(b, c, d, a, x[14], S34, 0xfde5380c); // 36
HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ HH(a, b, c, d, x[1], S31, 0xa4beea44); // 37
HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ HH(d, a, b, c, x[4], S32, 0x4bdecfa9); // 38
HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ HH(c, d, a, b, x[7], S33, 0xf6bb4b60); // 39
HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH(b, c, d, a, x[10], S34, 0xbebfbc70); // 40
HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH(a, b, c, d, x[13], S31, 0x289b7ec6); // 41
HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ HH(d, a, b, c, x[0], S32, 0xeaa127fa); // 42
HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ HH(c, d, a, b, x[3], S33, 0xd4ef3085); // 43
HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ HH(b, c, d, a, x[6], S34, 0x4881d05); // 44
HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ HH(a, b, c, d, x[9], S31, 0xd9d4d039); // 45
HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH(d, a, b, c, x[12], S32, 0xe6db99e5); // 46
HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH(c, d, a, b, x[15], S33, 0x1fa27cf8); // 47
HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ HH(b, c, d, a, x[2], S34, 0xc4ac5665); // 48
/* Round 4 */ // Round 4
II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ II(a, b, c, d, x[0], S41, 0xf4292244); // 49
II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ II(d, a, b, c, x[7], S42, 0x432aff97); // 50
II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II(c, d, a, b, x[14], S43, 0xab9423a7); // 51
II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ II(b, c, d, a, x[5], S44, 0xfc93a039); // 52
II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II(a, b, c, d, x[12], S41, 0x655b59c3); // 53
II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ II(d, a, b, c, x[3], S42, 0x8f0ccc92); // 54
II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II(c, d, a, b, x[10], S43, 0xffeff47d); // 55
II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ II(b, c, d, a, x[1], S44, 0x85845dd1); // 56
II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ II(a, b, c, d, x[8], S41, 0x6fa87e4f); // 57
II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II(d, a, b, c, x[15], S42, 0xfe2ce6e0); // 58
II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ II(c, d, a, b, x[6], S43, 0xa3014314); // 59
II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II(b, c, d, a, x[13], S44, 0x4e0811a1); // 60
II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ II(a, b, c, d, x[4], S41, 0xf7537e82); // 61
II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II(d, a, b, c, x[11], S42, 0xbd3af235); // 62
II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ II(c, d, a, b, x[2], S43, 0x2ad7d2bb); // 63
II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ II(b, c, d, a, x[9], S44, 0xeb86d391); // 64
state[0] += a; state[0] += a;
state[1] += b; state[1] += b;
state[2] += c; state[2] += c;
state[3] += d; state[3] += d;
// Zeroize sensitive information. // Zeroize sensitive information
memset((uint1 *)x, 0, sizeof(x)); memset((uint1 *)x, 0, sizeof(x));
} }
// Encodes input (UINT4) into output (unsigned char). Assumes len is // Encodes input (UINT4) into output (unsigned char). Assumes len is
// a multiple of 4. // a multiple of 4.
void MD5::encode(uint1 *output, uint4 *input, uint4 len) void MD5::encode(uint1 *output, uint4 *input, uint4 len)
{ {
unsigned int i, j; unsigned int i, j;
@ -393,6 +397,7 @@ void MD5::encode(uint1 *output, uint4 *input, uint4 len)
// Decodes input (unsigned char) into output (UINT4). Assumes len is // Decodes input (unsigned char) into output (UINT4). Assumes len is
// a multiple of 4. // a multiple of 4.
void MD5::decode(uint4 *output, uint1 *input, uint4 len) void MD5::decode(uint4 *output, uint1 *input, uint4 len)
{ {
unsigned int i, j; unsigned int i, j;
@ -403,7 +408,8 @@ void MD5::decode(uint4 *output, uint1 *input, uint4 len)
} }
} }
// Note: Replace "for loop" with standard memcpy if possible. // Note: Replace "for loop" with standard memcpy if possible
void MD5::memcpy(uint1 *output, uint1 *input, uint4 len) void MD5::memcpy(uint1 *output, uint1 *input, uint4 len)
{ {
unsigned int i; unsigned int i;
@ -414,7 +420,8 @@ void MD5::memcpy(uint1 *output, uint1 *input, uint4 len)
} }
} }
// Note: Replace "for loop" with standard memset if possible. // Note: Replace "for loop" with standard memset if possible
void MD5::memset(uint1 *output, uint1 value, uint4 len) void MD5::memset(uint1 *output, uint1 value, uint4 len)
{ {
unsigned int i; unsigned int i;
@ -425,14 +432,14 @@ void MD5::memset(uint1 *output, uint1 value, uint4 len)
} }
} }
// ROTATE_LEFT rotates x left n bits. // ROTATE_LEFT rotates x left n bits
inline unsigned int MD5::rotate_left(uint4 x, uint4 n) inline unsigned int MD5::rotate_left(uint4 x, uint4 n)
{ {
return (x << n) | (x >> (32 - n)); return (x << n) | (x >> (32 - n));
} }
// F, G, H and I are basic MD5 functions. // F, G, H and I are basic MD5 functions
inline unsigned int MD5::F(uint4 x, uint4 y, uint4 z) inline unsigned int MD5::F(uint4 x, uint4 y, uint4 z)
{ {

View File

@ -1,23 +1,23 @@
// MD5.CC - source code for the C++/object oriented translation and /*
// modification of MD5.
// Translation and modification (c) 1995 by Mordechai T. Abzug MD5.CC - source code for the C++/object oriented translation and modification of MD5.
// This translation/ modification is provided "as is," without express or Translation and modification (c) 1995 by Mordechai T. Abzug
// implied warranty of any kind.
// The translator/ modifier does not claim (1) that MD5 will do what you think This translation/ modification is provided "as is," without express or
// it does; (2) that this translation/ modification is accurate; or (3) that implied warranty of any kind.
// this software is "merchantible." (Language for this disclaimer partially
// copied from the disclaimer below).
/* based on: The translator/ modifier does not claim (1) that MD5 will do what you think
it does; (2) that this translation/ modification is accurate; or (3) that
this software is "merchantable." (Language for this disclaimer partially
copied from the disclaimer below).
based on:
MD5.H - header file for MD5C.C MD5.H - header file for MD5C.C
MDDRIVER.C - test driver for MD2, MD4 and MD5 MDDRIVER.C - test driver for MD2, MD4 and MD5
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.
rights reserved.
License to copy and use this software is granted provided that it License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest is identified as the "RSA Data Security, Inc. MD5 Message-Digest
@ -89,45 +89,43 @@ struct MD5Digest_less : std::binary_function < MD5Digest, MD5Digest, bool >
class MD5 class MD5
{ {
public: public:
// methods for controlled operation: // Methods for controlled operation:
MD5(); // simple initializer MD5(); // Simple initializer
~MD5(); ~MD5();
void update(const unsigned char *input, unsigned int input_length); void update(const unsigned char *input, unsigned int input_length);
void update(FILE *file); void update(FILE *file);
void finalize(); void finalize();
// constructors for special circumstances. All these constructors finalize // Constructors for special circumstances. All these constructors finalize the MD5 context.
// the MD5 context. MD5(CPath File); // Digest file, finalize
MD5(CPath File); // digest File, finalize MD5(const unsigned char *string); // Digest string, finalize
MD5(const unsigned char *string); // digest string, finalize MD5(FILE *file); // Digest file, close, finalize
MD5(FILE *file); // digest file, close, finalize
MD5(const unsigned char *input, unsigned int input_length); MD5(const unsigned char *input, unsigned int input_length);
MD5(const stdstr & string); MD5(const stdstr & string);
// methods to acquire finalized result // Methods to acquire finalized result
void get_digest(MD5Digest& extdigest); //Digest into a digest structure void get_digest(MD5Digest& extdigest); // Digest into a digest structure
const unsigned char *raw_digest(); // digest as a 16-byte binary array const unsigned char *raw_digest(); // Digest as a 16-byte binary array
const char * hex_digest(); // digest as a 33-byte ascii-hex string const char * hex_digest(); // Digest as a 33-byte ascii-hex string
private: private:
// first, some types: // First, some types:
typedef unsigned int uint4; // assumes integer is 4 words long typedef unsigned int uint4; // Assumes integer is 4 words long
typedef unsigned short int uint2; // assumes short integer is 2 words long typedef unsigned short int uint2; // Assumes short integer is 2 words long
typedef unsigned char uint1; // assumes char is 1 word long typedef unsigned char uint1; // Assumes char is 1 word long
// next, the private data: // Next, the private data:
uint4 state[4]; uint4 state[4];
uint4 count[2]; // number of *bits*, mod 2^64 uint4 count[2]; // Number of *bits*, mod 2^64
uint1 buffer[64]; // input buffer uint1 buffer[64]; // Input buffer
uint1 digest[16]; uint1 digest[16];
uint1 finalized; uint1 finalized;
stdstr m_hex_digest; stdstr m_hex_digest;
// last, the private methods, mostly static: // Last, the private methods, mostly static:
void init(); // called by all constructors void init(); // Called by all constructors
void transform(uint1 *buffer); // does the real update work. Note void transform(uint1 *buffer); // Does the real update work. Note that length is implied to be 64.
// that length is implied to be 64.
static void encode(uint1 *dest, uint4 *src, uint4 length); static void encode(uint1 *dest, uint4 *src, uint4 length);
static void decode(uint4 *dest, uint1 *src, uint4 length); static void decode(uint4 *dest, uint1 *src, uint4 length);

View File

@ -1,6 +1,5 @@
// Path.cpp: implementation of the CPath class. // Path.cpp: Implementation of the CPath class
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h" #include "stdafx.h"
#ifdef _WIN32 #ifdef _WIN32
#pragma warning(push) #pragma warning(push)
@ -18,10 +17,9 @@
#endif #endif
#include "Platform.h" #include "Platform.h"
/* // g_ModuleLogLevel may be NULL while AppInit() is still in session in path.cpp.
* g_ModuleLogLevel may be NULL while AppInit() is still in session in path.cpp. // The added check to compare to NULL here is at least a temporary workaround.
* The added check to compare to NULL here is at least a temporary workaround.
*/
#undef WriteTrace #undef WriteTrace
#ifdef _WIN32 #ifdef _WIN32
#define WriteTrace(m, s, format, ...) if (g_ModuleLogLevel != NULL && g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __FUNCTION__, (format), ## __VA_ARGS__); } #define WriteTrace(m, s, format, ...) if (g_ModuleLogLevel != NULL && g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __FUNCTION__, (format), ## __VA_ARGS__); }
@ -29,9 +27,7 @@
#define WriteTrace(m, s, format, ...) if (g_ModuleLogLevel != NULL && g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __PRETTY_FUNCTION__, (format), ## __VA_ARGS__); } #define WriteTrace(m, s, format, ...) if (g_ModuleLogLevel != NULL && g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __PRETTY_FUNCTION__, (format), ## __VA_ARGS__); }
#endif #endif
//////////////////////////////////////////////////////////////////////
// Constants // Constants
//////////////////////////////////////////////////////////////////////
#ifdef _WIN32 #ifdef _WIN32
const char DRIVE_DELIMITER = ':'; const char DRIVE_DELIMITER = ':';
@ -48,9 +44,8 @@ const char EXTENSION_DELIMITER = '.';
void * CPath::m_hInst = NULL; void * CPath::m_hInst = NULL;
#endif #endif
//////////////////////////////////////////////////////////////////////
// Helpers // Helpers
//////////////////////////////////////////////////////////////////////
#ifdef _WIN32 #ifdef _WIN32
void CPath::SethInst(void * hInst) void CPath::SethInst(void * hInst)
{ {
@ -62,15 +57,12 @@ void * CPath::GethInst()
return m_hInst; return m_hInst;
} }
#endif #endif
//////////////////////////////////////////////////////////////////////
// Initialisation
//////////////////////////////////////////////////////////////////////
//------------------------------------------------------------- // Initialization
// Task : Helper function for the various CPath constructors.
// Initializes the data members and establishes various // Task: Helper function for the various CPath constructors.
// class invariants // Initializes the data members and establishes various class invariants.
//-------------------------------------------------------------
inline void CPath::Init() inline void CPath::Init()
{ {
m_dwFindFileAttributes = 0; m_dwFindFileAttributes = 0;
@ -82,10 +74,8 @@ inline void CPath::Init()
#endif #endif
} }
//------------------------------------------------------------- // Task: Helper function for the various CPath destructors. Cleans up various internals.
// Task : Helper function for the various CPath destructors.
// Cleans up varios internals
//-------------------------------------------------------------
inline void CPath::Exit() inline void CPath::Exit()
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -103,31 +93,26 @@ inline void CPath::Exit()
#endif #endif
} }
//////////////////////////////////////////////////////////////////////
// Construction/Destruction // Construction/Destruction
//////////////////////////////////////////////////////////////////////
//------------------------------------------------------------- // Task: Constructs a path
// Task : Constructs a path
//-------------------------------------------------------------
CPath::CPath() CPath::CPath()
{ {
Init(); Init();
Empty(); Empty();
} }
//------------------------------------------------------------- // Task: Constructs a path as copy of another
// Task : Constructs a path as copy of another
//-------------------------------------------------------------
CPath::CPath(const CPath& rPath) CPath::CPath(const CPath& rPath)
{ {
Init(); Init();
m_strPath = rPath.m_strPath; m_strPath = rPath.m_strPath;
} }
//------------------------------------------------------------- // Task: Constructs a path and points it to lpszPath
// Task : Constructs a path and points it 2 lpszPath
//-------------------------------------------------------------
CPath::CPath(const char * lpszPath) CPath::CPath(const char * lpszPath)
{ {
Init(); Init();
@ -148,9 +133,8 @@ CPath::CPath(const char * lpszPath, const char * NameExten)
WriteTrace(TracePath, TraceDebug, "Done (m_strPath: \"%s\")", m_strPath.c_str()); WriteTrace(TracePath, TraceDebug, "Done (m_strPath: \"%s\")", m_strPath.c_str());
} }
//------------------------------------------------------------- // Task: Constructs a path and points it to strPath
// Task : Constructs a path and points it 2 strPath
//-------------------------------------------------------------
CPath::CPath(const std::string& strPath) CPath::CPath(const std::string& strPath)
{ {
Init(); Init();
@ -158,9 +142,8 @@ CPath::CPath(const std::string& strPath)
cleanPathString(m_strPath); cleanPathString(m_strPath);
} }
//------------------------------------------------------------- // Task: Constructs a path and points it to strPath
// Task : Constructs a path and points it 2 strPath
//-------------------------------------------------------------
CPath::CPath(const std::string& strPath, const char * NameExten) CPath::CPath(const std::string& strPath, const char * NameExten)
{ {
Init(); Init();
@ -172,9 +155,8 @@ CPath::CPath(const std::string& strPath, const char * NameExten)
SetNameExtension(NameExten); SetNameExtension(NameExten);
} }
//------------------------------------------------------------- // Task: Constructs a path and points it to strPath
// Task : Constructs a path and points it 2 strPath
//-------------------------------------------------------------
CPath::CPath(const std::string& strPath, const std::string& NameExten) CPath::CPath(const std::string& strPath, const std::string& NameExten)
{ {
Init(); Init();
@ -186,18 +168,16 @@ CPath::CPath(const std::string& strPath, const std::string& NameExten)
SetNameExtension(NameExten.c_str()); SetNameExtension(NameExten.c_str());
} }
//------------------------------------------------------------- // Task: Cleanup and destruct a path object
// Task : Cleanup and destruct a path object
//-------------------------------------------------------------
CPath::~CPath() CPath::~CPath()
{ {
Exit(); Exit();
} }
//------------------------------------------------------------- // Post: Return TRUE if paths are equal
// Post : Return TRUE if paths are equal // Task: Check if the two path are the same
// Task : Check if the two path are the same
//-------------------------------------------------------------
bool CPath::operator ==(const CPath& rPath) const bool CPath::operator ==(const CPath& rPath) const
{ {
// Get fully qualified versions of the paths // Get fully qualified versions of the paths
@ -211,18 +191,16 @@ bool CPath::operator ==(const CPath& rPath) const
return _stricmp(FullyQualified1.c_str(), FullyQualified2.c_str()) == 0; return _stricmp(FullyQualified1.c_str(), FullyQualified2.c_str()) == 0;
} }
//------------------------------------------------------------- // Post: Return TRUE if paths are different
// Post : Return TRUE if paths are different // Task: Check if the two path are different
// Task : Check if the two path are different
//-------------------------------------------------------------
bool CPath::operator !=(const CPath& rPath) const bool CPath::operator !=(const CPath& rPath) const
{ {
return !(*this == rPath); return !(*this == rPath);
} }
//------------------------------------------------------------- // Task: Assign a path to another
// Task : Assign a path 2 another
//-------------------------------------------------------------
CPath& CPath::operator =(const CPath& rPath) CPath& CPath::operator =(const CPath& rPath)
{ {
if (this != &rPath) if (this != &rPath)
@ -232,34 +210,33 @@ CPath& CPath::operator =(const CPath& rPath)
return *this; return *this;
} }
//------------------------------------------------------------- // Post: Return the path, so that assignments can be chained
// Post : Return the path, so that assignements can be chained // Task: Assign a string to a path
// Task : Assign a string 2 a path
//-------------------------------------------------------------
CPath& CPath::operator =(const char * lpszPath) CPath& CPath::operator =(const char * lpszPath)
{ {
m_strPath = lpszPath ? lpszPath : ""; m_strPath = lpszPath ? lpszPath : "";
return *this; return *this;
} }
//------------------------------------------------------------- // Post: Return the path, so that assignments can be chained
// Post : Return the path, so that assignements can be chained // Task: Assign a string to a path
// Task : Assign a string 2 a path
//-------------------------------------------------------------
CPath& CPath::operator =(const std::string& strPath) CPath& CPath::operator =(const std::string& strPath)
{ {
m_strPath = strPath; m_strPath = strPath;
return *this; return *this;
} }
//------------------------------------------------------------- /*
// Post : Converts path 2 string Post: Converts path to string
// Task : Convert path 2 string Task: Convert path to string
// Warning: because this pointer 2 string point in the data Warning: because this pointer to string point in the data
// of this class, it is possible 2 cast the result of this of this class, it is possible to cast the result of this
// function in any non-constant pointer and alter the data. function in any non-constant pointer and alter the data.
// Very dangerous Very dangerous!
//------------------------------------------------------------- */
CPath::operator const char *() const CPath::operator const char *() const
{ {
return (const char *)m_strPath.c_str(); return (const char *)m_strPath.c_str();
@ -290,20 +267,21 @@ CPath::CPath(DIR_MODULE_FILE /*sdt*/)
} }
#endif #endif
//------------------------------------------------------------- /*
// Post : Returns the drive component without a colon, e.g. "c" Post: Returns the drive component without a colon, e.g. "c"
// Returns the directory component with a leading backslash, Returns the directory component with a leading backslash,
// but no trailing backslash, e.g. "\dir\subdir" but no trailing backslash, e.g. "\dir\subdir"
// Returns name compleletely without delimiters, e.g "letter" Returns name completely without delimiters, e.g "letter"
// Returns extension completely without delimiters, e.g. "doc" Returns extension completely without delimiters, e.g. "doc"
// Globals : Globals:
// I/O : I/O:
// Task : Return the individual components of this path. Task: Return the individual components of this path.
// For any given argument, you can pass NULL if you are not For any given argument, you can pass NULL if you are not
// interested in that component. interested in that component.
// Do not rely on pNames being <= 8 characters, extensions Do not rely on pNames being <= 8 characters, extensions
// being <= 3 characters, or drives being 1 character being <= 3 characters, or drives being 1 character
//------------------------------------------------------------- */
#ifdef _WIN32 #ifdef _WIN32
void CPath::GetComponents(std::string* pDrive, std::string* pDirectory, std::string* pName, std::string* pExtension) const void CPath::GetComponents(std::string* pDrive, std::string* pDirectory, std::string* pName, std::string* pExtension) const
{ {
@ -423,9 +401,8 @@ void CPath::GetComponents(std::string* pDirectory, std::string* pName, std::stri
} }
#endif #endif
//------------------------------------------------------------- // Task: Get drive and directory from path
// Task : Get drive and directory from path
//-------------------------------------------------------------
#ifdef _WIN32 #ifdef _WIN32
void CPath::GetDriveDirectory(std::string& rDriveDirectory) const void CPath::GetDriveDirectory(std::string& rDriveDirectory) const
{ {
@ -449,9 +426,8 @@ std::string CPath::GetDriveDirectory(void) const
} }
#endif #endif
//------------------------------------------------------------- // Task: Get directory from path
// Task : Get directory from path
//-------------------------------------------------------------
void CPath::GetDirectory(std::string& rDirectory) const void CPath::GetDirectory(std::string& rDirectory) const
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -468,9 +444,8 @@ std::string CPath::GetDirectory(void) const
return rDirectory; return rDirectory;
} }
//------------------------------------------------------------- // Task: Get filename and extension from path
// Task : Get filename and extension from path
//-------------------------------------------------------------
void CPath::GetNameExtension(std::string& rNameExtension) const void CPath::GetNameExtension(std::string& rNameExtension) const
{ {
std::string Name; std::string Name;
@ -496,9 +471,8 @@ std::string CPath::GetNameExtension(void) const
return rNameExtension; return rNameExtension;
} }
//------------------------------------------------------------- // Task: Get filename from path
// Task : Get filename from path
//-------------------------------------------------------------
void CPath::GetName(std::string& rName) const void CPath::GetName(std::string& rName) const
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -515,9 +489,8 @@ std::string CPath::GetName(void) const
return rName; return rName;
} }
//------------------------------------------------------------- // Task: Get file extension from path
// Task : Get file extension from path
//-------------------------------------------------------------
void CPath::GetExtension(std::string& rExtension) const void CPath::GetExtension(std::string& rExtension) const
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -534,9 +507,8 @@ std::string CPath::GetExtension(void) const
return rExtension; return rExtension;
} }
//------------------------------------------------------------- // Task: Get current directory
// Task : Get current directory
//-------------------------------------------------------------
void CPath::GetLastDirectory(std::string& rDirectory) const void CPath::GetLastDirectory(std::string& rDirectory) const
{ {
std::string Directory; std::string Directory;
@ -562,9 +534,8 @@ std::string CPath::GetLastDirectory(void) const
return rDirecotry; return rDirecotry;
} }
//------------------------------------------------------------- // Task: Get fully qualified path
// Task : Get fully qualified path
//-------------------------------------------------------------
void CPath::GetFullyQualified(std::string& rFullyQualified) const void CPath::GetFullyQualified(std::string& rFullyQualified) const
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -577,10 +548,9 @@ void CPath::GetFullyQualified(std::string& rFullyQualified) const
#endif #endif
} }
//------------------------------------------------------------- // Post: Return TRUE if path does not start from filesystem root
// Post : Return TRUE if path does not start from filesystem root // Task: Check if path is a relative one (e.g. doesn't start with C:\...)
// Task : Check if path is a relative one (e.g. doesn't start with C:\...)
//-------------------------------------------------------------
bool CPath::IsRelative() const bool CPath::IsRelative() const
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -601,9 +571,8 @@ bool CPath::IsRelative() const
return true; return true;
} }
//------------------------------------------------------------- // Task: Set path components
// Task : Set path components
//-------------------------------------------------------------
#ifdef _WIN32 #ifdef _WIN32
void CPath::SetComponents(const char * lpszDrive, const char * lpszDirectory, const char * lpszName, const char * lpszExtension) void CPath::SetComponents(const char * lpszDrive, const char * lpszDirectory, const char * lpszName, const char * lpszExtension)
{ {
@ -648,15 +617,14 @@ void CPath::SetComponents(const char * lpszDirectory, const char * lpszName, con
} }
strncat(buff_fullname,lpszExtension,sizeof(buff_fullname)-1); strncat(buff_fullname,lpszExtension,sizeof(buff_fullname)-1);
} }
buff_fullname[sizeof(buff_fullname) - 1] = 0; //Make sure it is null terminated buff_fullname[sizeof(buff_fullname) - 1] = 0; // Make sure it is null terminated
m_strPath.erase(); m_strPath.erase();
m_strPath = buff_fullname; m_strPath = buff_fullname;
} }
#endif #endif
//------------------------------------------------------------- // Task: Set path's drive
// Task : Set path's drive
//-------------------------------------------------------------
#ifdef _WIN32 #ifdef _WIN32
void CPath::SetDrive(char chDrive) void CPath::SetDrive(char chDrive)
{ {
@ -670,12 +638,11 @@ void CPath::SetDrive(char chDrive)
} }
#endif #endif
//------------------------------------------------------------- // Task: Set path's directory
// Task : Set path's directory
//-------------------------------------------------------------
void CPath::SetDirectory(const char * lpszDirectory, bool bEnsureAbsolute /*= false*/) void CPath::SetDirectory(const char * lpszDirectory, bool bEnsureAbsolute /*= false*/)
{ {
WriteTrace(TracePath, TraceDebug, "start (lpszDirectory: \"%s\" bEnsureAbsolute: %s)", lpszDirectory ? lpszDirectory : "(null)", bEnsureAbsolute ? "true" : "false"); WriteTrace(TracePath, TraceDebug, "Start (lpszDirectory: \"%s\" bEnsureAbsolute: %s)", lpszDirectory ? lpszDirectory : "(null)", bEnsureAbsolute ? "true" : "false");
std::string Directory = lpszDirectory; std::string Directory = lpszDirectory;
std::string Name; std::string Name;
std::string Extension; std::string Extension;
@ -701,9 +668,9 @@ void CPath::SetDirectory(const char * lpszDirectory, bool bEnsureAbsolute /*= fa
} }
#ifdef _WIN32 #ifdef _WIN32
//-------------------------------------------------------------
// Task : Set path's drive and directory // Task: Set path's drive and directory
//-------------------------------------------------------------
void CPath::SetDriveDirectory(const char * lpszDriveDirectory) void CPath::SetDriveDirectory(const char * lpszDriveDirectory)
{ {
std::string DriveDirectory = lpszDriveDirectory; std::string DriveDirectory = lpszDriveDirectory;
@ -721,9 +688,8 @@ void CPath::SetDriveDirectory(const char * lpszDriveDirectory)
} }
#endif #endif
//------------------------------------------------------------- // Task: Set path's filename
// Task : Set path's filename
//-------------------------------------------------------------
void CPath::SetName(const char * lpszName) void CPath::SetName(const char * lpszName)
{ {
std::string Directory; std::string Directory;
@ -739,9 +705,8 @@ void CPath::SetName(const char * lpszName)
#endif #endif
} }
//------------------------------------------------------------- // Task: Set path's filename
// Task : Set path's filename
//-------------------------------------------------------------
void CPath::SetName(int iName) void CPath::SetName(int iName)
{ {
std::string Directory; std::string Directory;
@ -762,9 +727,8 @@ void CPath::SetName(int iName)
#endif #endif
} }
//------------------------------------------------------------- // Task: Set path's file extension
// Task : Set path's file extension
//-------------------------------------------------------------
void CPath::SetExtension(const char * lpszExtension) void CPath::SetExtension(const char * lpszExtension)
{ {
std::string Directory; std::string Directory;
@ -780,9 +744,8 @@ void CPath::SetExtension(const char * lpszExtension)
#endif #endif
} }
//------------------------------------------------------------- // Task: Set path's file extension
// Task : Set path's file extension
//-------------------------------------------------------------
void CPath::SetExtension(int iExtension) void CPath::SetExtension(int iExtension)
{ {
std::string Directory; std::string Directory;
@ -803,9 +766,8 @@ void CPath::SetExtension(int iExtension)
#endif #endif
} }
//------------------------------------------------------------- // Task: Set path's filename and extension
// Task : Set path's filename and extension
//-------------------------------------------------------------
void CPath::SetNameExtension(const char * lpszNameExtension) void CPath::SetNameExtension(const char * lpszNameExtension)
{ {
std::string Directory; std::string Directory;
@ -820,9 +782,8 @@ void CPath::SetNameExtension(const char * lpszNameExtension)
#endif #endif
} }
//------------------------------------------------------------- // Task: Append a subdirectory to path's directory
// Task : Append a subdirectory 2 path's directory
//-------------------------------------------------------------
void CPath::AppendDirectory(const char * lpszSubDirectory) void CPath::AppendDirectory(const char * lpszSubDirectory)
{ {
std::string Directory; std::string Directory;
@ -835,7 +796,7 @@ void CPath::AppendDirectory(const char * lpszSubDirectory)
return; return;
} }
// Strip out any preceeding backslash // Strip out any preceding backslash
StripLeadingBackslash(SubDirectory); StripLeadingBackslash(SubDirectory);
EnsureTrailingBackslash(SubDirectory); EnsureTrailingBackslash(SubDirectory);
@ -855,11 +816,12 @@ void CPath::AppendDirectory(const char * lpszSubDirectory)
#endif #endif
} }
//------------------------------------------------------------- /*
// Pre : If pLastDirectory is given we will store the name of the Pre: If pLastDirectory is given we will store the name of the
// deepest directory (the one we're just exiting) in it deepest directory (the one we're exiting) in it
// Task : Remove deepest subdirectory from path Task: Remove deepest subdirectory from path
//------------------------------------------------------------- */
void CPath::UpDirectory(std::string *pLastDirectory /*= NULL*/) void CPath::UpDirectory(std::string *pLastDirectory /*= NULL*/)
{ {
std::string Directory; std::string Directory;
@ -885,9 +847,8 @@ void CPath::UpDirectory(std::string *pLastDirectory /*= NULL*/)
SetDirectory(Directory.c_str()); SetDirectory(Directory.c_str());
} }
//------------------------------------------------------------- // Task: Set path to current directory
// Task : Set path 2 current directory
//-------------------------------------------------------------
void CPath::CurrentDirectory() void CPath::CurrentDirectory()
{ {
char buff_path[260]; char buff_path[260];
@ -904,9 +865,8 @@ void CPath::CurrentDirectory()
#endif #endif
} }
//------------------------------------------------------------- // Task: Set path to the name of specified module
// Task : Set path 2 the name of specified module
//-------------------------------------------------------------
#ifdef _WIN32 #ifdef _WIN32
void CPath::Module(void * hInstance) void CPath::Module(void * hInstance)
{ {
@ -918,26 +878,23 @@ void CPath::Module(void * hInstance)
m_strPath = buff_path; m_strPath = buff_path;
} }
//------------------------------------------------------------- // Task: Set path to the name of current module
// Task : Set path 2 the name of current module
//-------------------------------------------------------------
void CPath::Module() void CPath::Module()
{ {
Module(m_hInst); Module(m_hInst);
} }
//------------------------------------------------------------- // Task: Set path to the directory of specified module
// Task : Set path 2 the directory of specified module
//-------------------------------------------------------------
void CPath::ModuleDirectory(void * hInstance) void CPath::ModuleDirectory(void * hInstance)
{ {
Module(hInstance); Module(hInstance);
SetNameExtension(""); SetNameExtension("");
} }
//------------------------------------------------------------- // Task: Set path to the directory of current module
// Task : Set path 2 the directory of current module
//-------------------------------------------------------------
void CPath::ModuleDirectory() void CPath::ModuleDirectory()
{ {
Module(); Module();
@ -945,10 +902,9 @@ void CPath::ModuleDirectory()
} }
#endif #endif
//--------------------------------------------------------------------------- // Post: Return TRUE if it is a directory
// Post : Return TRUE if a directory // Task: Check if this path represents a directory
// Task : Check if this path represents a directory
//---------------------------------------------------------------------------
bool CPath::IsDirectory() const bool CPath::IsDirectory() const
{ {
// Check if this path has a filename // Check if this path has a filename
@ -958,14 +914,15 @@ bool CPath::IsDirectory() const
return file_name.empty(); return file_name.empty();
} }
//------------------------------------------------------------- /*
// Post : Return TRUE if directory exists Post: Return TRUE if directory exists
// Task : To determine if the directory exists, we need to Task: To determine if the directory exists, we need to
// create a test path with a wildcard (*.*) extension create a test path with a wildcard (*.*) extension
// and see if FindFirstFile returns anything. We don't and see if FindFirstFile returns anything. We don't
// use CPath::FindFirst() because that routine parses out use CPath::FindFirst() because that routine parses out
// '.' and '..', which fails for empty directories '.' and '..', which fails for empty directories
//------------------------------------------------------------- */
bool CPath::DirectoryExists() const bool CPath::DirectoryExists() const
{ {
WriteTrace(TracePath, TraceDebug, "m_strPath = %s",m_strPath.c_str()); WriteTrace(TracePath, TraceDebug, "m_strPath = %s",m_strPath.c_str());
@ -999,10 +956,9 @@ bool CPath::DirectoryExists() const
return res; return res;
} }
//------------------------------------------------------------- // Post: Return TRUE if these is such a file
// Post : Return TRUE if these is such a file // Task: Check if file exists
// Task : Check if file exists
//-------------------------------------------------------------
bool CPath::Exists() const bool CPath::Exists() const
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -1055,23 +1011,22 @@ bool CPath::SelectFile(void * hwndOwner, const char * InitialDir, const char * F
} }
#endif #endif
//------------------------------------------------------------- // Post: Return TRUE on success
// Post : Return TRUE on success // Task: Delete file
// Task : Delete file
//-------------------------------------------------------------
bool CPath::Delete(bool bEvenIfReadOnly) const bool CPath::Delete(bool bEvenIfReadOnly) const
{ {
#ifdef _WIN32 #ifdef _WIN32
uint32_t dwAttr = ::GetFileAttributesA(m_strPath.c_str()); uint32_t dwAttr = ::GetFileAttributesA(m_strPath.c_str());
if (dwAttr == (uint32_t)-1) if (dwAttr == (uint32_t)-1)
{ {
// File does not exist. // File does not exist
return false; return false;
} }
if (((dwAttr & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY) && !bEvenIfReadOnly) if (((dwAttr & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY) && !bEvenIfReadOnly)
{ {
// File is read-only, and we're not allowed 2 delete it // File is read-only, and we're not allowed to delete it
return false; return false;
} }
@ -1082,13 +1037,14 @@ bool CPath::Delete(bool bEvenIfReadOnly) const
#endif #endif
} }
//------------------------------------------------------------- /*
// Post : Return TRUE on success, false if there is such a target file Post: Return TRUE on success, false if there is such a target file
// and we weren't granted permission 2 overwrite file or some error and we weren't granted permission to overwrite file or if we get an error
// Task : Copy file Task: Copy file
// Since ::CopyFile will not overwrite read only files Since ::CopyFile will not overwrite read-only files
// we will make sure the target file is writable first we will make sure the target file is writable first
//------------------------------------------------------------- */
bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite) bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
{ {
if (lpcszTargetFile == NULL) if (lpcszTargetFile == NULL)
@ -1115,50 +1071,50 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
} }
} }
// CopyFile will set the target's attributes 2 the same as // CopyFile will set the target's attributes to the same as
// the source after copying // the source after copying
return CopyFileA(m_strPath.c_str(), lpcszTargetFile, !bOverwrite) != 0; return CopyFileA(m_strPath.c_str(), lpcszTargetFile, !bOverwrite) != 0;
#else #else
bool res = true; bool res = true;
WriteTrace(TracePath, TraceDebug, "opening \"%s\" for reading",m_strPath.c_str()); WriteTrace(TracePath, TraceDebug, "Opening \"%s\" for reading",m_strPath.c_str());
FILE * infile = fopen(m_strPath.c_str(), "rb"); FILE * infile = fopen(m_strPath.c_str(), "rb");
if(infile == NULL) if(infile == NULL)
{ {
WriteTrace(TracePath, TraceWarning, "failed to open m_strPath = %s",m_strPath.c_str()); WriteTrace(TracePath, TraceWarning, "Failed to open m_strPath = %s",m_strPath.c_str());
res = false; res = false;
} }
else else
{ {
WriteTrace(TracePath, TraceDebug, "opened \"%s\"",m_strPath.c_str()); WriteTrace(TracePath, TraceDebug, "Opened \"%s\"",m_strPath.c_str());
} }
FILE * outfile = NULL; FILE * outfile = NULL;
if (res) if (res)
{ {
WriteTrace(TracePath, TraceDebug, "opening \"%s\" for writing",lpcszTargetFile); WriteTrace(TracePath, TraceDebug, "Opening \"%s\" for writing",lpcszTargetFile);
outfile = fopen(lpcszTargetFile, "wb"); outfile = fopen(lpcszTargetFile, "wb");
if (outfile == NULL) if (outfile == NULL)
{ {
WriteTrace(TracePath, TraceWarning, "failed to open m_strPath = %s errno=%d",lpcszTargetFile, errno); WriteTrace(TracePath, TraceWarning, "Failed to open m_strPath = %s errno=%d",lpcszTargetFile, errno);
res = false; res = false;
} }
else else
{ {
WriteTrace(TracePath, TraceDebug, "opened \"%s\"",lpcszTargetFile); WriteTrace(TracePath, TraceDebug, "Opened \"%s\"",lpcszTargetFile);
} }
} }
if (res) if (res)
{ {
WriteTrace(TracePath, TraceDebug, "copying data"); WriteTrace(TracePath, TraceDebug, "Copying data");
while (!feof(infile)) while (!feof(infile))
{ {
char buffer[1024]; char buffer[1024];
size_t bytes = fread(buffer, 1, sizeof(buffer), infile); size_t bytes = fread(buffer, 1, sizeof(buffer), infile);
if (ferror(infile)) if (ferror(infile))
{ {
WriteTrace(TracePath, TraceWarning, "failed to read from %s", m_strPath.c_str()); WriteTrace(TracePath, TraceWarning, "Failed to read from %s", m_strPath.c_str());
res = false; res = false;
break; break;
} }
@ -1168,7 +1124,7 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
} }
if (ferror(outfile)) if (ferror(outfile))
{ {
WriteTrace(TracePath, TraceWarning, "failed to write to %s, ferror(outfile) = %X", lpcszTargetFile, ferror(outfile)); WriteTrace(TracePath, TraceWarning, "Failed to write to %s, ferror(outfile) = %X", lpcszTargetFile, ferror(outfile));
res = false; res = false;
break; break;
} }
@ -1205,11 +1161,10 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
#endif #endif
} }
//------------------------------------------------------------- // Post: Return TRUE on success, false if there is such a target file
// Post : Return TRUE on success, false if there is such a target file // and we weren't granted permission to overwrite file or get an error
// and we weren't granted permission 2 overwrite file or some error // Task: Move file
// Task : Move file
//-------------------------------------------------------------
bool CPath::MoveTo(const char * lpcszTargetFile, bool bOverwrite) bool CPath::MoveTo(const char * lpcszTargetFile, bool bOverwrite)
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -1237,10 +1192,9 @@ bool CPath::MoveTo(const char * lpcszTargetFile, bool bOverwrite)
#endif #endif
} }
//------------------------------------------------------------- // Post: Return TRUE if attributes match
// Post : Return TRUE if attributes do match // Task: Compare finder attributes
// Task : Compare finder attributes
//-------------------------------------------------------------
bool CPath::AttributesMatch(uint32_t dwTargetAttributes, uint32_t dwFileAttributes) bool CPath::AttributesMatch(uint32_t dwTargetAttributes, uint32_t dwFileAttributes)
{ {
if (dwTargetAttributes == FIND_ATTRIBUTE_ALLFILES) if (dwTargetAttributes == FIND_ATTRIBUTE_ALLFILES)
@ -1254,34 +1208,28 @@ bool CPath::AttributesMatch(uint32_t dwTargetAttributes, uint32_t dwFileAttribut
return (((dwTargetAttributes & dwFileAttributes) != 0) && ((FIND_ATTRIBUTE_SUBDIR & dwTargetAttributes) == (FIND_ATTRIBUTE_SUBDIR & dwFileAttributes))); return (((dwTargetAttributes & dwFileAttributes) != 0) && ((FIND_ATTRIBUTE_SUBDIR & dwTargetAttributes) == (FIND_ATTRIBUTE_SUBDIR & dwFileAttributes)));
} }
//------------------------------------------------------------- /*
// Post : Return TRUE if any match found Post: Return TRUE if any match found
// Task : Find the first file that meets this path and the specified attributes Task: Find the first file that meets this path and the specified attributes
// You can specify the current attributes of the file or directory You can specify the current attributes of the file or directory
// The attributes are represented by a combination (|) of the following The attributes are represented by a combination (|) of the following
// constants: constants:
// _A_ARCH - Archive. Set whenever the file is changed, and cleared by the BACKUP command.
// _A_ARCH Archive. Set whenever the file is _A_HIDDEN - Hidden file. Not normally seen with the DIR command, unless the /AH option is used.
// changed, and cleared by the BACKUP command Returns information about normal files as well as files with this attribute:
// _A_HIDDEN Hidden file. Not normally seen with FIND_ATTRIBUTE_FILES - Normal. File can be read or written to without restriction.
// the DIR command, unless the /AH option _A_RDONLY - Read-only. File cannot be opened for writing, and a file with the same name cannot be created.
// is used. Returns information about normal FIND_ATTRIBUTE_SUBDIR - Subdirectory
// files as well as files with this attribute _A_SYSTEM - System file. Not normally seen with the DIR command, unless the /AS option is used.
// FIND_ATTRIBUTE_FILES Normal. File can be read or written to
// without restriction These attributes do not follow a simple additive logic.
// _A_RDONLY Read-only. File cannot be opened for writing, Note that FIND_ATTRIBUTE_FILES is 0x00, so it effectively cannot be
// and a file with the same name cannot be created removed from the attribute set. You will therefore always
// FIND_ATTRIBUTE_SUBDIR Subdirectory get normal files, and may also get Archive, Hidden, etc.
// _A_SYSTEM System file. Not normally seen with the DIR if you specify those attributes
// command, unless the /AS option is used See also: FindFirstFile, FindNextFile
// */
// These attributes do not follow a simple additive logic
// Note that FIND_ATTRIBUTE_FILES is 0x00, so it effectively cannot be
// removed from the attribute set. You will therefore always
// get normal files, and may also get Archive, Hidden, etc.
// if you specify those attributes
// See aso: FindFirstFile, FindNextFile
//-------------------------------------------------------------
bool CPath::FindFirst(uint32_t dwAttributes /*= FIND_ATTRIBUTE_FILES*/) bool CPath::FindFirst(uint32_t dwAttributes /*= FIND_ATTRIBUTE_FILES*/)
{ {
// Close handle to any previous enumeration // Close handle to any previous enumeration
@ -1292,20 +1240,20 @@ bool CPath::FindFirst(uint32_t dwAttributes /*= FIND_ATTRIBUTE_FILES*/)
BOOL bGotFile; BOOL bGotFile;
BOOL bWantSubdirectory = (BOOL)(FIND_ATTRIBUTE_SUBDIR & dwAttributes); BOOL bWantSubdirectory = (BOOL)(FIND_ATTRIBUTE_SUBDIR & dwAttributes);
// i.) Finding first candidate file // Finding first candidate file
WIN32_FIND_DATAA FindData; WIN32_FIND_DATAA FindData;
m_hFindFile = FindFirstFileA(m_strPath.c_str(), &FindData); m_hFindFile = FindFirstFileA(m_strPath.c_str(), &FindData);
bGotFile = (m_hFindFile != INVALID_HANDLE_VALUE); bGotFile = (m_hFindFile != INVALID_HANDLE_VALUE);
while (bGotFile) while (bGotFile)
{ {
// ii.) Compare candidate to attributes, and filter out the "." and ".." folders // Compare candidate to attributes, and filter out the "." and ".." folders
if (!AttributesMatch(m_dwFindFileAttributes, FindData.dwFileAttributes)) if (!AttributesMatch(m_dwFindFileAttributes, FindData.dwFileAttributes))
goto LABEL_GetAnother; goto LABEL_GetAnother;
if (bWantSubdirectory && (FindData.cFileName[0] == '.')) if (bWantSubdirectory && (FindData.cFileName[0] == '.'))
goto LABEL_GetAnother; goto LABEL_GetAnother;
// iii.) Found match, prepare result // Found a match, prepare result
if ((FIND_ATTRIBUTE_SUBDIR & FindData.dwFileAttributes) != 0) if ((FIND_ATTRIBUTE_SUBDIR & FindData.dwFileAttributes) != 0)
StripTrailingBackslash(m_strPath); StripTrailingBackslash(m_strPath);
@ -1315,7 +1263,7 @@ bool CPath::FindFirst(uint32_t dwAttributes /*= FIND_ATTRIBUTE_FILES*/)
EnsureTrailingBackslash(m_strPath); EnsureTrailingBackslash(m_strPath);
return TRUE; return TRUE;
// iv.) Not found match, get another // Not found a match, get another
LABEL_GetAnother: LABEL_GetAnother:
bGotFile = FindNextFileA(m_hFindFile, &FindData); bGotFile = FindNextFileA(m_hFindFile, &FindData);
} }
@ -1337,11 +1285,9 @@ bool CPath::FindFirst(uint32_t dwAttributes /*= FIND_ATTRIBUTE_FILES*/)
return false; return false;
} }
//-------------------------------------------------------------
// Post : Return TRUE if a new match found // Post : Return TRUE if a new match found
// Task : Find the next file that meets the conditions specified // Task : Find the next file that meets the conditions specified in the last FindFirst call
// in the last FindFirst call
//-------------------------------------------------------------
bool CPath::FindNext() bool CPath::FindNext()
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -1393,7 +1339,7 @@ bool CPath::FindNext()
WriteTrace(TracePath, TraceVerbose, "m_dwFindFileAttributes = %X dwFileAttributes = %X AttributesMatch: %s",m_dwFindFileAttributes, dwFileAttributes, AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) ? "true" : "false"); WriteTrace(TracePath, TraceVerbose, "m_dwFindFileAttributes = %X dwFileAttributes = %X AttributesMatch: %s",m_dwFindFileAttributes, dwFileAttributes, AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) ? "true" : "false");
// ii.) Compare candidate to attributes, and filter out the "." and ".." folders // Compare candidate to attributes, and filter out the "." and ".." folders
if (!AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) || if (!AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) ||
strcmp(pEntry->d_name,".") == 0 || strcmp(pEntry->d_name,".") == 0 ||
strcmp(pEntry->d_name,"..") == 0 || strcmp(pEntry->d_name,"..") == 0 ||
@ -1438,10 +1384,9 @@ bool CPath::FindNext()
return false; return false;
} }
//------------------------------------------------------------- // Post: Return TRUE on success
// Post : Return TRUE on success // Task: Change current working directory of application to path
// Task : Change current working directory of application 2 path
//-------------------------------------------------------------
bool CPath::ChangeDirectory() bool CPath::ChangeDirectory()
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -1504,12 +1449,10 @@ void CPath::NormalizePath(CPath BaseDir)
} }
} }
//------------------------------------------------------------- // Pre: If bCreateIntermediates is TRUE, create all eventually missing parent directories too
// Pre : If bCreateIntermediates is TRUE, create all eventually // Post: Return TRUE on success
// missing parent directories too // Task: Create new directory
// Post : Return TRUE on success
// Task : Create new directory
//-------------------------------------------------------------
bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/) bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
{ {
WriteTrace(TracePath, TraceDebug, "m_strPath = %s bCreateIntermediates = %s",m_strPath.c_str(),bCreateIntermediates ? "true" : "false"); WriteTrace(TracePath, TraceDebug, "m_strPath = %s bCreateIntermediates = %s",m_strPath.c_str(),bCreateIntermediates ? "true" : "false");
@ -1534,12 +1477,12 @@ bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
bSuccess = mkdir(PathText.c_str(), S_IRWXU) == 0; bSuccess = mkdir(PathText.c_str(), S_IRWXU) == 0;
if (!bSuccess) if (!bSuccess)
{ {
WriteTrace(TracePath, TraceWarning, "failed to create \"%s\" errno: %d",PathText.c_str(), errno); WriteTrace(TracePath, TraceWarning, "Failed to create \"%s\" errno: %d",PathText.c_str(), errno);
} }
#endif #endif
if (!bSuccess && bCreateIntermediates) if (!bSuccess && bCreateIntermediates)
{ {
WriteTrace(TracePath, TraceDebug, "failed creating intermediates"); WriteTrace(TracePath, TraceDebug, "Failed creating intermediates");
std::string::size_type nDelimiter = PathText.rfind(DIRECTORY_DELIMITER); std::string::size_type nDelimiter = PathText.rfind(DIRECTORY_DELIMITER);
if (nDelimiter == std::string::npos) if (nDelimiter == std::string::npos)
{ {
@ -1555,11 +1498,10 @@ bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
return bSuccess; return bSuccess;
} }
//Helpers // Helpers
// Task: Remove first character (if any) if it's chLeading
//------------------------------------------------------------------------
// Task : Remove first character (if any) if it's chLeading
//------------------------------------------------------------------------
void CPath::cleanPathString(std::string& rDirectory) const void CPath::cleanPathString(std::string& rDirectory) const
{ {
std::string::size_type pos = rDirectory.find(DIRECTORY_DELIMITER2); std::string::size_type pos = rDirectory.find(DIRECTORY_DELIMITER2);
@ -1592,14 +1534,13 @@ void CPath::StripLeadingChar(std::string& rText, char chLeading) const
rText = rText.substr(1); rText = rText.substr(1);
} }
//------------------------------------------------------------------------ // Task: Remove first character if '\'
// Task : Remove first character if \
//------------------------------------------------------------------------
void CPath::StripLeadingBackslash(std::string& Directory) const void CPath::StripLeadingBackslash(std::string& Directory) const
{ {
std::string::size_type nLength = Directory.length(); std::string::size_type nLength = Directory.length();
// If Directory is of the form '\', don't do it // If directory is of the form '\', don't do it
if (nLength <= 1) if (nLength <= 1)
return; return;
@ -1607,9 +1548,8 @@ void CPath::StripLeadingBackslash(std::string& Directory) const
Directory = Directory.substr(1); Directory = Directory.substr(1);
} }
//------------------------------------------------------------------------ // Task: Remove last character (if any) if it's chTrailing
// Task : Remove last character (if any) if it's chTrailing
//------------------------------------------------------------------------
void CPath::StripTrailingChar(std::string& rText, char chTrailing) const void CPath::StripTrailingChar(std::string& rText, char chTrailing) const
{ {
std::string::size_type nLength = rText.length(); std::string::size_type nLength = rText.length();
@ -1620,9 +1560,8 @@ void CPath::StripTrailingChar(std::string& rText, char chTrailing) const
rText.resize(nLength - 1); rText.resize(nLength - 1);
} }
//------------------------------------------------------------------------ // Task: Remove last character if '\'
// Task : Remove last character if \
//------------------------------------------------------------------------
void CPath::StripTrailingBackslash(std::string& rDirectory) const void CPath::StripTrailingBackslash(std::string& rDirectory) const
{ {
for (;;) for (;;)
@ -1642,10 +1581,8 @@ void CPath::StripTrailingBackslash(std::string& rDirectory) const
} }
} }
//------------------------------------------------------------------------ // Task: Add a backslash to the end of the directory if there is not already one there
// Task : Add a backslash to the end of Directory if there is
// not already one there
//------------------------------------------------------------------------
void CPath::EnsureTrailingBackslash(std::string& Directory) const void CPath::EnsureTrailingBackslash(std::string& Directory) const
{ {
std::string::size_type nLength = Directory.length(); std::string::size_type nLength = Directory.length();
@ -1656,10 +1593,8 @@ void CPath::EnsureTrailingBackslash(std::string& Directory) const
} }
} }
//------------------------------------------------------------------------ // Task: Add a backslash to the beginning of the directory if there is not already one there
// Task : Add a backslash to the beginning of Directory if there
// is not already one there
//------------------------------------------------------------------------
void CPath::EnsureLeadingBackslash(std::string & Directory) const void CPath::EnsureLeadingBackslash(std::string & Directory) const
{ {
if (Directory.empty() || (Directory[0] != DIRECTORY_DELIMITER)) if (Directory.empty() || (Directory[0] != DIRECTORY_DELIMITER))

View File

@ -4,7 +4,7 @@
class CPath class CPath
{ {
//Enums // Enums
public: public:
enum DIR_CURRENT_DIRECTORY { CURRENT_DIRECTORY = 1 }; enum DIR_CURRENT_DIRECTORY { CURRENT_DIRECTORY = 1 };
@ -15,12 +15,12 @@ public:
enum enum
{ {
FIND_ATTRIBUTE_ALLFILES = 0xFFFF, // Search Include all files FIND_ATTRIBUTE_ALLFILES = 0xFFFF, // Search include all files
FIND_ATTRIBUTE_FILES = 0x0000, // File can be read or written to without restriction FIND_ATTRIBUTE_FILES = 0x0000, // File can be read or written to without restriction
FIND_ATTRIBUTE_SUBDIR = 0x0010, // Subdirectories FIND_ATTRIBUTE_SUBDIR = 0x0010, // Subdirectories
}; };
//Attributes // Attributes
private: private:
std::string m_strPath; std::string m_strPath;
#ifdef _WIN32 #ifdef _WIN32
@ -33,9 +33,9 @@ private:
uint32_t m_dwFindFileAttributes; uint32_t m_dwFindFileAttributes;
public: public:
//Methods // Methods
//Construction / destruction // Construction / destruction
CPath(); CPath();
CPath(const CPath& rPath); CPath(const CPath& rPath);
CPath(const char * lpszPath); CPath(const char * lpszPath);
@ -51,7 +51,7 @@ public:
#endif #endif
virtual ~CPath(); virtual ~CPath();
//Operators // Operators
CPath& operator = (const CPath& rPath); CPath& operator = (const CPath& rPath);
CPath& operator = (const char * lpszPath); CPath& operator = (const char * lpszPath);
CPath& operator = (const std::string & strPath); CPath& operator = (const std::string & strPath);
@ -60,7 +60,7 @@ public:
operator const char *() const; operator const char *() const;
operator const std::string &() { return m_strPath; } operator const std::string &() { return m_strPath; }
//Get path components // Get path components
#ifdef _WIN32 #ifdef _WIN32
void GetDriveDirectory(std::string & rDriveDirectory) const; void GetDriveDirectory(std::string & rDriveDirectory) const;
std::string GetDriveDirectory(void) const; std::string GetDriveDirectory(void) const;
@ -81,11 +81,11 @@ public:
#else #else
void GetComponents(std::string* pDirectory = NULL, std::string* pName = NULL, std::string* pExtension = NULL) const; void GetComponents(std::string* pDirectory = NULL, std::string* pName = NULL, std::string* pExtension = NULL) const;
#endif #endif
//Get other state // Get other state
bool IsEmpty() const { return m_strPath.empty(); } bool IsEmpty() const { return m_strPath.empty(); }
bool IsRelative() const; bool IsRelative() const;
//Set path components // Set path components
#ifdef _WIN32 #ifdef _WIN32
void SetDrive(char chDrive); void SetDrive(char chDrive);
void SetDriveDirectory(const char * lpszDriveDirectory); void SetDriveDirectory(const char * lpszDriveDirectory);
@ -103,7 +103,7 @@ public:
#else #else
void SetComponents(const char * lpszDirectory, const char * lpszName, const char * lpszExtension); void SetComponents(const char * lpszDirectory, const char * lpszName, const char * lpszExtension);
#endif #endif
//Set whole path // Set whole path
void Empty() { m_strPath.erase(); } void Empty() { m_strPath.erase(); }
void CurrentDirectory(); void CurrentDirectory();
#ifdef _WIN32 #ifdef _WIN32
@ -113,28 +113,28 @@ public:
void ModuleDirectory(void * hInstance); void ModuleDirectory(void * hInstance);
#endif #endif
//Directory information // Directory information
bool IsDirectory() const; bool IsDirectory() const;
bool DirectoryExists() const; bool DirectoryExists() const;
//File Information // File information
bool IsFile() const { return !IsDirectory(); } bool IsFile() const { return !IsDirectory(); }
bool Exists() const; bool Exists() const;
#ifdef _WIN32 #ifdef _WIN32
bool SelectFile(void * hwndOwner, const char * InitialDir, const char * FileFilter, bool FileMustExist); bool SelectFile(void * hwndOwner, const char * InitialDir, const char * FileFilter, bool FileMustExist);
#endif #endif
//Directory operations // Directory operations
bool DirectoryCreate(bool bCreateIntermediates = true); bool DirectoryCreate(bool bCreateIntermediates = true);
bool ChangeDirectory(); bool ChangeDirectory();
void NormalizePath(CPath BaseDir); void NormalizePath(CPath BaseDir);
//File operations // File operations
bool Delete(bool bEvenIfReadOnly = true) const; bool Delete(bool bEvenIfReadOnly = true) const;
bool CopyTo(const char * lpcszTargetFile, bool bOverwrite = true); bool CopyTo(const char * lpcszTargetFile, bool bOverwrite = true);
bool MoveTo(const char * lpcszTargetFile, bool bOverwrite = true); bool MoveTo(const char * lpcszTargetFile, bool bOverwrite = true);
//Finders // Finders
bool FindFirst(uint32_t dwAttributes = 0); bool FindFirst(uint32_t dwAttributes = 0);
bool FindNext(); bool FindNext();
@ -145,7 +145,7 @@ public:
#endif #endif
private: private:
//Setup & Cleanup // Setup and cleanup
inline void Init(); inline void Init();
inline void Exit(); inline void Exit();

View File

@ -1,9 +1,8 @@
#pragma once #pragma once
/* // Some versions of Microsoft Visual C/++ compilers before Visual Studio 2010
* Some versions of Microsoft Visual C/++ compilers before Visual Studio 2010 // have <stdint.h> removed in favor of these non-standard built-in types:
* have <stdint.h> removed in favor of these nonstandard built-in types:
*/
#if defined(_MSC_VER) && (_MSC_VER < 1600) #if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef signed __int8 int8_t; typedef signed __int8 int8_t;
typedef signed __int16 int16_t; typedef signed __int16 int16_t;