1
0

sprintf() begone! Replaced with StringUtils' Printf()

git-svn-id: http://mc-server.googlecode.com/svn/trunk@216 0a769ca7-a7f5-676a-18bf-c427514a06d6
This commit is contained in:
madmaxoft@gmail.com 2012-02-01 13:43:47 +00:00
parent d3614be2e0
commit 2568bad3cc
18 changed files with 429 additions and 292 deletions

View File

@ -38,11 +38,13 @@ using namespace std;
#endif
#ifndef _WIN32
#define sprintf_s(buffer, buffer_size, stringbuffer, ...) (sprintf(buffer, stringbuffer, __VA_ARGS__))
#define vsprintf_s(buffer, stringbuffer, ...) (vsprintf(buffer, stringbuffer, __VA_ARGS__))
#define sscanf_s(buffer, stringbuffer, ...) (sscanf(buffer, stringbuffer, __VA_ARGS__))
#endif
cIniFile::cIniFile( const string iniPath)
{
Path( iniPath);
@ -115,6 +117,10 @@ bool cIniFile::ReadFile()
return false;
}
bool cIniFile::WriteFile()
{
unsigned commentID, keyID, valueID;
@ -148,6 +154,10 @@ bool cIniFile::WriteFile()
return true;
}
long cIniFile::FindKey( const string & keyname) const
{
for ( unsigned keyID = 0; keyID < names.size(); ++keyID)
@ -156,6 +166,10 @@ long cIniFile::FindKey( const string & keyname) const
return noID;
}
long cIniFile::FindValue( unsigned const keyID, const string & valuename) const
{
if ( !keys.size() || keyID >= keys.size())
@ -167,6 +181,10 @@ long cIniFile::FindValue( unsigned const keyID, const string & valuename) const
return noID;
}
unsigned cIniFile::AddKeyName( const string & keyname)
{
names.resize( names.size() + 1, keyname);
@ -174,6 +192,10 @@ unsigned cIniFile::AddKeyName( const string & keyname)
return names.size() - 1;
}
string cIniFile::KeyName( unsigned const keyID) const
{
if ( keyID < names.size())
@ -182,6 +204,10 @@ string cIniFile::KeyName( unsigned const keyID) const
return "";
}
unsigned cIniFile::NumValues( unsigned const keyID)
{
if ( keyID < keys.size())
@ -189,6 +215,10 @@ unsigned cIniFile::NumValues( unsigned const keyID)
return 0;
}
unsigned cIniFile::NumValues( const string & keyname)
{
long keyID = FindKey( keyname);
@ -197,6 +227,10 @@ unsigned cIniFile::NumValues( const string & keyname)
return keys[keyID].names.size();
}
string cIniFile::ValueName( unsigned const keyID, unsigned const valueID) const
{
if ( keyID < keys.size() && valueID < keys[keyID].names.size())
@ -204,6 +238,10 @@ string cIniFile::ValueName( unsigned const keyID, unsigned const valueID) const
return "";
}
string cIniFile::ValueName( const string & keyname, unsigned const valueID) const
{
long keyID = FindKey( keyname);
@ -212,6 +250,10 @@ string cIniFile::ValueName( const string & keyname, unsigned const valueID) cons
return ValueName( keyID, valueID);
}
bool cIniFile::SetValue( unsigned const keyID, unsigned const valueID, const string & value)
{
if ( keyID < keys.size() && valueID < keys[keyID].names.size())
@ -220,6 +262,10 @@ bool cIniFile::SetValue( unsigned const keyID, unsigned const valueID, const str
return false;
}
bool cIniFile::SetValue( const string & keyname, const string & valuename, const string & value, bool const create)
{
long keyID = FindKey( keyname);
@ -250,33 +296,48 @@ bool cIniFile::SetValue( const string & keyname, const string & valuename, const
return true;
}
bool cIniFile::SetValueI( const string & keyname, const string & valuename, int const value, bool const create)
{
char svalue[MAX_VALUEDATA];
sprintf_s( svalue, MAX_VALUEDATA, "%d", value);
return SetValue( keyname, valuename, svalue, create);
AString Data;
Printf(Data, "%d", value);
return SetValue( keyname, valuename, Data, create);
}
bool cIniFile::SetValueF( const string & keyname, const string & valuename, double const value, bool const create)
{
char svalue[MAX_VALUEDATA];
sprintf_s( svalue, MAX_VALUEDATA, "%f", value);
return SetValue( keyname, valuename, svalue, create);
AString Data;
Printf(Data, "%f", value);
return SetValue( keyname, valuename, Data, create);
}
bool cIniFile::SetValueV( const string & keyname, const string & valuename, char *format, ...)
{
va_list args;
char value[MAX_VALUEDATA];
va_start( args, format);
vsprintf_s( value, format, args);
AString Data;
AppendVPrintf(Data, format, args);
va_end( args);
return SetValue( keyname, valuename, value );
return SetValue( keyname, valuename, Data);
}
string cIniFile::GetValue( unsigned const keyID, unsigned const valueID, const string & defValue) const
{
if ( keyID < keys.size() && valueID < keys[keyID].names.size())
@ -284,6 +345,10 @@ string cIniFile::GetValue( unsigned const keyID, unsigned const valueID, const s
return defValue;
}
string cIniFile::GetValue( const string & keyname, const string & valuename, const string & defValue) const
{
long keyID = FindKey( keyname);
@ -297,22 +362,32 @@ string cIniFile::GetValue( const string & keyname, const string & valuename, con
return keys[keyID].values[valueID];
}
int cIniFile::GetValueI(const string & keyname, const string & valuename, int const defValue) const
{
char svalue[MAX_VALUEDATA];
sprintf_s( svalue, MAX_VALUEDATA, "%d", defValue);
return atoi( GetValue( keyname, valuename, svalue).c_str());
AString Data;
Printf(Data, "%d", defValue);
return atoi( GetValue( keyname, valuename, Data).c_str());
}
double cIniFile::GetValueF(const string & keyname, const string & valuename, double const defValue) const
{
char svalue[MAX_VALUEDATA];
sprintf_s( svalue, MAX_VALUEDATA, "%f", defValue);
return atof( GetValue( keyname, valuename, svalue).c_str());
AString Data;
Printf(Data, "%f", defValue);
return atof( GetValue( keyname, valuename, Data).c_str());
}
// 16 variables may be a bit of over kill, but hey, it's only code.
unsigned cIniFile::GetValueV( const string & keyname, const string & valuename, char *format,
void *v1, void *v2, void *v3, void *v4,
@ -342,6 +417,10 @@ unsigned cIniFile::GetValueV( const string & keyname, const string & valuename,
return nVals;
}
bool cIniFile::DeleteValueByID( const unsigned keyID, const unsigned valueID )
{
if ( keyID < keys.size() && valueID < keys[keyID].names.size())

View File

@ -12,174 +12,177 @@
//////////////////////////////////////////////////////////////////////
/*
!! MODIFIED BY FAKETRUTH !!
!! MODIFIED BY FAKETRUTH and madmaxoft!!
*/
#ifndef CIniFile_H
#define CIniFile_H
// C++ Includes
#include <string>
#include <vector>
// C Includes
#include <stdlib.h>
#define MAX_KEYNAME 128
#define MAX_VALUENAME 128
#define MAX_VALUEDATA 2048
class cIniFile //tolua_export
{ //tolua_export
private:
bool caseInsensitive;
std::string path;
struct key {
std::vector<std::string> names;
std::vector<std::string> values;
bool caseInsensitive;
std::string path;
struct key {
std::vector<std::string> names;
std::vector<std::string> values;
std::vector<std::string> comments;
};
std::vector<key> keys;
std::vector<std::string> names;
std::vector<std::string> comments;
};
std::vector<key> keys;
std::vector<std::string> names;
std::vector<std::string> comments;
std::string CheckCase( std::string s) const;
std::string CheckCase( std::string s) const;
public:
enum errors{ noID = -1}; //tolua_export
cIniFile( const std::string iniPath = ""); //tolua_export
virtual ~cIniFile() {}
enum errors{ noID = -1}; //tolua_export
cIniFile( const std::string iniPath = ""); //tolua_export
virtual ~cIniFile() {}
// Sets whether or not keynames and valuenames should be case sensitive.
// The default is case insensitive.
void CaseSensitive() {caseInsensitive = false;} //tolua_export
void CaseInsensitive() {caseInsensitive = true;} //tolua_export
// Sets whether or not keynames and valuenames should be case sensitive.
// The default is case insensitive.
void CaseSensitive() {caseInsensitive = false;} //tolua_export
void CaseInsensitive() {caseInsensitive = true;} //tolua_export
// Sets path of ini file to read and write from.
void Path(const std::string & newPath) {path = newPath;} //tolua_export
std::string Path() const {return path;} //tolua_export
void SetPath(const std::string & newPath) {Path( newPath);} //tolua_export
// Sets path of ini file to read and write from.
void Path(const std::string & newPath) {path = newPath;} //tolua_export
std::string Path() const {return path;} //tolua_export
void SetPath(const std::string & newPath) {Path( newPath);} //tolua_export
// Reads ini file specified using path.
// Returns true if successful, false otherwise.
bool ReadFile(); //tolua_export
// Writes data stored in class to ini file.
bool WriteFile(); //tolua_export
// Deletes all stored ini data.
void Erase(); //tolua_export
void Clear() {Erase();} //tolua_export
void Reset() {Erase();} //tolua_export
// Reads ini file specified using path.
// Returns true if successful, false otherwise.
bool ReadFile(); //tolua_export
// Returns index of specified key, or noID if not found.
long FindKey( const std::string & keyname) const; //tolua_export
// Writes data stored in class to ini file.
bool WriteFile(); //tolua_export
// Returns index of specified value, in the specified key, or noID if not found.
long FindValue( const unsigned keyID, const std::string & valuename) const; //tolua_export
// Deletes all stored ini data.
void Erase(); //tolua_export
void Clear() {Erase();} //tolua_export
void Reset() {Erase();} //tolua_export
// Returns number of keys currently in the ini.
unsigned NumKeys() const {return names.size();} //tolua_export
unsigned GetNumKeys() const {return NumKeys();} //tolua_export
// Returns index of specified key, or noID if not found.
long FindKey( const std::string & keyname) const; //tolua_export
// Add a key name.
unsigned AddKeyName( const std::string & keyname); //tolua_export
// Returns index of specified value, in the specified key, or noID if not found.
long FindValue( const unsigned keyID, const std::string & valuename) const; //tolua_export
// Returns key names by index.
std::string KeyName( const unsigned keyID) const; //tolua_export
std::string GetKeyName( const unsigned keyID) const {return KeyName(keyID);} //tolua_export
// Returns number of keys currently in the ini.
unsigned NumKeys() const {return names.size();} //tolua_export
unsigned GetNumKeys() const {return NumKeys();} //tolua_export
// Returns number of values stored for specified key.
unsigned NumValues( const std::string & keyname); //tolua_export
unsigned GetNumValues( const std::string & keyname) {return NumValues( keyname);} //tolua_export
unsigned NumValues( const unsigned keyID); //tolua_export
unsigned GetNumValues( const unsigned keyID) {return NumValues( keyID);} //tolua_export
// Add a key name.
unsigned AddKeyName( const std::string & keyname); //tolua_export
// Returns value name by index for a given keyname or keyID.
std::string ValueName( const std::string & keyname, const unsigned valueID) const; //tolua_export
std::string GetValueName( const std::string & keyname, const unsigned valueID) const { //tolua_export
return ValueName( keyname, valueID);
} //tolua_export
std::string ValueName( const unsigned keyID, const unsigned valueID) const; //tolua_export
std::string GetValueName( const unsigned keyID, const unsigned valueID) const { //tolua_export
return ValueName( keyID, valueID);
} //tolua_export
// Returns key names by index.
std::string KeyName( const unsigned keyID) const; //tolua_export
std::string GetKeyName( const unsigned keyID) const {return KeyName(keyID);} //tolua_export
// Gets value of [keyname] valuename =.
// Overloaded to return string, int, and double.
// Returns defValue if key/value not found.
std::string GetValue( const std::string & keyname, const std::string & valuename, const std::string & defValue = "") const; //tolua_export
std::string GetValue( const unsigned keyID, const unsigned valueID, const std::string & defValue = "") const; //tolua_export
int GetValueI( const std::string & keyname, const std::string & valuename, const int defValue = 0) const; //tolua_export
bool GetValueB( const std::string & keyname, const std::string & valuename, const bool defValue = false) const { //tolua_export
return ( GetValueI( keyname, valuename, int( defValue)) > 0);
} //tolua_export
double GetValueF( const std::string & keyname, const std::string & valuename, const double defValue = 0.0) const; //tolua_export
// This is a variable length formatted GetValue routine. All these voids
// are required because there is no vsscanf() like there is a vsprintf().
// Only a maximum of 8 variable can be read.
unsigned GetValueV( const std::string & keyname, const std::string & valuename, char *format,
void *v1 = 0, void *v2 = 0, void *v3 = 0, void *v4 = 0,
void *v5 = 0, void *v6 = 0, void *v7 = 0, void *v8 = 0,
void *v9 = 0, void *v10 = 0, void *v11 = 0, void *v12 = 0,
void *v13 = 0, void *v14 = 0, void *v15 = 0, void *v16 = 0);
// Returns number of values stored for specified key.
unsigned NumValues( const std::string & keyname); //tolua_export
unsigned GetNumValues( const std::string & keyname) {return NumValues( keyname);} //tolua_export
unsigned NumValues( const unsigned keyID); //tolua_export
unsigned GetNumValues( const unsigned keyID) {return NumValues( keyID);} //tolua_export
// Sets value of [keyname] valuename =.
// Specify the optional paramter as false (0) if you do not want it to create
// the key if it doesn't exist. Returns true if data entered, false otherwise.
// Overloaded to accept string, int, and double.
bool SetValue( const unsigned keyID, const unsigned valueID, const std::string & value); //tolua_export
bool SetValue( const std::string & keyname, const std::string & valuename, const std::string & value, const bool create = true); //tolua_export
bool SetValueI( const std::string & keyname, const std::string & valuename, const int value, const bool create = true); //tolua_export
bool SetValueB( const std::string & keyname, const std::string & valuename, const bool value, const bool create = true) { //tolua_export
return SetValueI( keyname, valuename, int(value), create);
} //tolua_export
bool SetValueF( const std::string & keyname, const std::string & valuename, const double value, const bool create = true); //tolua_export
bool SetValueV( const std::string & keyname, const std::string & valuename, char *format, ...);
// Returns value name by index for a given keyname or keyID.
std::string ValueName( const std::string & keyname, const unsigned valueID) const; //tolua_export
std::string GetValueName( const std::string & keyname, const unsigned valueID) const { //tolua_export
return ValueName( keyname, valueID);
} //tolua_export
std::string ValueName( const unsigned keyID, const unsigned valueID) const; //tolua_export
std::string GetValueName( const unsigned keyID, const unsigned valueID) const { //tolua_export
return ValueName( keyID, valueID);
} //tolua_export
// Deletes specified value.
// Returns true if value existed and deleted, false otherwise.
bool DeleteValueByID( const unsigned keyID, const unsigned valueID ); //tolua_export
bool DeleteValue( const std::string & keyname, const std::string & valuename); //tolua_export
// Deletes specified key and all values contained within.
// Returns true if key existed and deleted, false otherwise.
bool DeleteKey(const std::string & keyname); //tolua_export
// Gets value of [keyname] valuename =.
// Overloaded to return string, int, and double.
// Returns defValue if key/value not found.
std::string GetValue( const std::string & keyname, const std::string & valuename, const std::string & defValue = "") const; //tolua_export
std::string GetValue( const unsigned keyID, const unsigned valueID, const std::string & defValue = "") const; //tolua_export
int GetValueI( const std::string & keyname, const std::string & valuename, const int defValue = 0) const; //tolua_export
bool GetValueB( const std::string & keyname, const std::string & valuename, const bool defValue = false) const { //tolua_export
return ( GetValueI( keyname, valuename, int( defValue)) > 0);
} //tolua_export
double GetValueF( const std::string & keyname, const std::string & valuename, const double defValue = 0.0) const; //tolua_export
// Header comment functions.
// Header comments are those comments before the first key.
//
// Number of header comments.
unsigned NumHeaderComments() {return comments.size();} //tolua_export
// Add a header comment.
void HeaderComment( const std::string & comment); //tolua_export
// Return a header comment.
std::string HeaderComment( const unsigned commentID) const; //tolua_export
// Delete a header comment.
bool DeleteHeaderComment( unsigned commentID); //tolua_export
// Delete all header comments.
void DeleteHeaderComments() {comments.clear();} //tolua_export
// This is a variable length formatted GetValue routine. All these voids
// are required because there is no vsscanf() like there is a vsprintf().
// Only a maximum of 8 variable can be read.
// NOTE: do not use this function, instead get the string value and parse it yourself
OBSOLETE unsigned GetValueV( const std::string & keyname, const std::string & valuename, char *format,
void *v1 = 0, void *v2 = 0, void *v3 = 0, void *v4 = 0,
void *v5 = 0, void *v6 = 0, void *v7 = 0, void *v8 = 0,
void *v9 = 0, void *v10 = 0, void *v11 = 0, void *v12 = 0,
void *v13 = 0, void *v14 = 0, void *v15 = 0, void *v16 = 0);
// Key comment functions.
// Key comments are those comments within a key. Any comments
// defined within value names will be added to this list. Therefore,
// these comments will be moved to the top of the key definition when
// the CIniFile::WriteFile() is called.
//
// Number of key comments.
unsigned NumKeyComments( const unsigned keyID) const; //tolua_export
unsigned NumKeyComments( const std::string & keyname) const; //tolua_export
// Add a key comment.
bool KeyComment( const unsigned keyID, const std::string & comment); //tolua_export
bool KeyComment( const std::string & keyname, const std::string & comment); //tolua_export
// Return a key comment.
std::string KeyComment( const unsigned keyID, const unsigned commentID) const; //tolua_export
std::string KeyComment( const std::string & keyname, const unsigned commentID) const; //tolua_export
// Delete a key comment.
bool DeleteKeyComment( const unsigned keyID, const unsigned commentID); //tolua_export
bool DeleteKeyComment( const std::string & keyname, const unsigned commentID); //tolua_export
// Delete all comments for a key.
bool DeleteKeyComments( const unsigned keyID); //tolua_export
bool DeleteKeyComments( const std::string & keyname); //tolua_export
// Sets value of [keyname] valuename =.
// Specify the optional paramter as false (0) if you do not want it to create
// the key if it doesn't exist. Returns true if data entered, false otherwise.
// Overloaded to accept string, int, and double.
bool SetValue( const unsigned keyID, const unsigned valueID, const std::string & value); //tolua_export
bool SetValue( const std::string & keyname, const std::string & valuename, const std::string & value, const bool create = true); //tolua_export
bool SetValueI( const std::string & keyname, const std::string & valuename, const int value, const bool create = true); //tolua_export
bool SetValueB( const std::string & keyname, const std::string & valuename, const bool value, const bool create = true) { //tolua_export
return SetValueI( keyname, valuename, int(value), create);
} //tolua_export
bool SetValueF( const std::string & keyname, const std::string & valuename, const double value, const bool create = true); //tolua_export
bool SetValueV( const std::string & keyname, const std::string & valuename, char *format, ...);
// Deletes specified value.
// Returns true if value existed and deleted, false otherwise.
bool DeleteValueByID( const unsigned keyID, const unsigned valueID ); //tolua_export
bool DeleteValue( const std::string & keyname, const std::string & valuename); //tolua_export
// Deletes specified key and all values contained within.
// Returns true if key existed and deleted, false otherwise.
bool DeleteKey(const std::string & keyname); //tolua_export
// Header comment functions.
// Header comments are those comments before the first key.
//
// Number of header comments.
unsigned NumHeaderComments() {return comments.size();} //tolua_export
// Add a header comment.
void HeaderComment( const std::string & comment); //tolua_export
// Return a header comment.
std::string HeaderComment( const unsigned commentID) const; //tolua_export
// Delete a header comment.
bool DeleteHeaderComment( unsigned commentID); //tolua_export
// Delete all header comments.
void DeleteHeaderComments() {comments.clear();} //tolua_export
// Key comment functions.
// Key comments are those comments within a key. Any comments
// defined within value names will be added to this list. Therefore,
// these comments will be moved to the top of the key definition when
// the CIniFile::WriteFile() is called.
//
// Number of key comments.
unsigned NumKeyComments( const unsigned keyID) const; //tolua_export
unsigned NumKeyComments( const std::string & keyname) const; //tolua_export
// Add a key comment.
bool KeyComment( const unsigned keyID, const std::string & comment); //tolua_export
bool KeyComment( const std::string & keyname, const std::string & comment); //tolua_export
// Return a key comment.
std::string KeyComment( const unsigned keyID, const unsigned commentID) const; //tolua_export
std::string KeyComment( const std::string & keyname, const unsigned commentID) const; //tolua_export
// Delete a key comment.
bool DeleteKeyComment( const unsigned keyID, const unsigned commentID); //tolua_export
bool DeleteKeyComment( const std::string & keyname, const unsigned commentID); //tolua_export
// Delete all comments for a key.
bool DeleteKeyComments( const unsigned keyID); //tolua_export
bool DeleteKeyComments( const std::string & keyname); //tolua_export
}; //tolua_export
#endif

View File

@ -80,11 +80,12 @@
/// Evaluates to the number of elements in an array (compile-time!)
#define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X)))
// sprintf_s is the preferred call in MSVC ("secure"); make it *nix-compatible:
#ifndef _WIN32
#define sprintf_s(dst, size, format, ...) sprintf(dst, format, __VA_ARGS__ )
#define vsnprintf_s(buffer, buffer_size, maxcount, stringbuffer, ...) (vsnprintf(buffer, maxcount, stringbuffer, __VA_ARGS__))
#endif // _WIN32
#ifdef _MSC_VER
#define OBSOLETE __declspec(deprecated)
#else
// TODO: how do other compilers mark functions as obsolete, so that their usage results in a compile-time warning?
#define OBSOLETE
#endif

View File

@ -899,8 +899,8 @@ cBlockEntity* cChunk::GetBlockEntity( int a_X, int a_Y, int a_Z )
/// Loads the chunk from the old-format disk file, erases the file afterwards. Returns true if successful
bool cChunk::LoadFromDisk()
{
char SourceFile[128];
sprintf_s(SourceFile, ARRAYCOUNT(SourceFile), "world/X%i_Y%i_Z%i.bin", m_PosX, m_PosY, m_PosZ );
AString SourceFile;
Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", m_PosX, m_PosY, m_PosZ );
cFile f;
if (!f.Open(SourceFile, cFile::fmRead))
@ -974,7 +974,7 @@ bool cChunk::LoadFromDisk()
f.Close();
// Delete old format file
if (std::remove(SourceFile) != 0)
if (std::remove(SourceFile.c_str()) != 0)
{
LOGERROR("Could not delete file %s", SourceFile );
}

View File

@ -105,8 +105,8 @@ bool cChunkLoader::SaveChunk( const cChunk & a_Chunk )
cChunk* cChunkLoader::LoadOldFormat( int a_X, int a_Y, int a_Z )
{
char SourceFile[128];
sprintf_s(SourceFile, 128, "world/X%i_Y%i_Z%i.bin", a_X, a_Y, a_Z );
AString SourceFile;
Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", a_X, a_Y, a_Z );
FILE* f = 0;
#ifdef _WIN32
@ -181,10 +181,10 @@ cChunk* cChunkLoader::LoadOldFormat( int a_X, int a_Y, int a_Z )
bool cChunkLoader::SaveOldFormat( const cChunk & a_Chunk )
{
char SourceFile[128];
sprintf_s(SourceFile, 128, "world/X%i_Y%i_Z%i.bin", a_Chunk.m_PosX, a_Chunk.m_PosY, a_Chunk.m_PosZ );
AString SourceFile;
Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", a_Chunk.m_PosX, a_Chunk.m_PosY, a_Chunk.m_PosZ );
#ifdef _WIN32
#ifdef _WIN32
{
SECURITY_ATTRIBUTES Attrib;
Attrib.nLength = sizeof(SECURITY_ATTRIBUTES);
@ -310,8 +310,8 @@ cChunk* cChunkLoader::LoadFormat1( int a_X, int a_Y, int a_Z )
cChunkLoader::ChunkPack* cChunkLoader::LoadPak1( int PakX, int PakY, int PakZ )
{
char SourceFile[128];
sprintf_s(SourceFile, 128, "world/X%i_Y%i_Z%i.pak", PakX, PakY, PakZ );
AString SourceFile;
Printf(SourceFile, "world/X%i_Y%i_Z%i.pak", PakX, PakY, PakZ );
FILE* f = 0;
#ifdef _WIN32

View File

@ -455,9 +455,8 @@ void cChunkMap::SaveLayer( cChunkLayer* a_Layer )
std::string WorldName = m_World->GetName();
cMakeDir::MakeDir( WorldName.c_str() );
char SourceFile[128];
sprintf_s(SourceFile, ARRAYCOUNT(SourceFile), ( WorldName + "/X%i_Z%i.pak").c_str(), a_Layer->m_X, a_Layer->m_Z );
AString SourceFile;
Printf(SourceFile, "%s/X%i_Z%i.pak", WorldName.c_str(), a_Layer->m_X, a_Layer->m_Z );
cFile f;
if (!f.Open(SourceFile, cFile::fmWrite))
@ -538,9 +537,9 @@ void cChunkMap::SaveLayer( cChunkLayer* a_Layer )
cChunkMap::cChunkLayer* cChunkMap::LoadLayer(int a_LayerX, int a_LayerZ )
{
std::string WorldName = m_World->GetName();
char SourceFile[128];
sprintf_s(SourceFile, ARRAYCOUNT(SourceFile), (WorldName + "/X%i_Z%i.pak").c_str(), a_LayerX, a_LayerZ );
AString SourceFile;
Printf(SourceFile, "%s/X%i_Z%i.pak", WorldName.c_str(), a_LayerX, a_LayerZ);
cFile f(SourceFile, cFile::fmRead);
if (!f.IsOpen())

View File

@ -507,11 +507,15 @@ void cClientHandle::HandlePacket( cPacket* a_Packet )
case E_PING: // Somebody tries to retrieve information about the server
{
LOGINFO("Got ping");
char NumPlayers[8], cMaxPlayers[8];
sprintf_s(NumPlayers, 8, "%i", cRoot::Get()->GetWorld()->GetNumPlayers());
sprintf_s(cMaxPlayers, 8, "%i", cRoot::Get()->GetWorld()->GetMaxPlayers());
std::string response = std::string(cRoot::Get()->GetWorld()->GetDescription() + cChatColor::Delimiter + NumPlayers + cChatColor::Delimiter + cMaxPlayers );
Kick( response.c_str() );
AString Reply;
Printf(Reply, "%s%s%i%s%i",
cRoot::Get()->GetWorld()->GetDescription().c_str(),
cChatColor::Delimiter.c_str(),
cRoot::Get()->GetWorld()->GetNumPlayers(),
cChatColor::Delimiter.c_str(),
cRoot::Get()->GetWorld()->GetMaxPlayers()
);
Kick(Reply.c_str());
}
break;
case E_HANDSHAKE:
@ -1659,9 +1663,9 @@ void cClientHandle::ReceiveThread( void *lpParam )
LOG("Unknown packet: 0x%02x \'%c\' %i", (unsigned char)temp, (unsigned char)temp, (unsigned char)temp );
char c_Str[128];
sprintf_s( c_Str, 128, "[C->S] Unknown PacketID: 0x%02x", (unsigned char)temp );
cPacket_Disconnect DC(c_Str);
AString Reason;
Printf(Reason, "[C->S] Unknown PacketID: 0x%02x", (unsigned char)temp );
cPacket_Disconnect DC(Reason);
DC.Send( socket );
cSleep::MilliSleep( 1000 ); // Give packet some time to be received

View File

@ -34,9 +34,9 @@ cEvent::cEvent(void)
delete m_Event;
m_bIsNamed = true;
char c_Str[64];
sprintf(c_Str, "cEvent%p", this);
m_Event = sem_open( c_Str, O_CREAT, 777, 0 );
AString EventName;
Printf(EventName, "cEvent%p", this);
m_Event = sem_open(EventName.c_str(), O_CREAT, 777, 0 );
if (m_Event == SEM_FAILED)
{
LOGERROR("cEvent: Cannot create event, errno = %i. Aborting server.", errno);

View File

@ -28,7 +28,7 @@ cFile::cFile(void) :
/// Constructs and opens / creates the file specified, use IsOpen() to check for success
cFile::cFile(const char * iFileName, EMode iMode) :
cFile::cFile(const AString & iFileName, EMode iMode) :
#ifdef USE_STDIO_FILE
m_File(NULL)
#else
@ -55,7 +55,7 @@ cFile::~cFile()
bool cFile::Open(const char * iFileName, EMode iMode)
bool cFile::Open(const AString & iFileName, EMode iMode)
{
assert(!IsOpen()); // You should close the file before opening another one
@ -76,7 +76,7 @@ bool cFile::Open(const char * iFileName, EMode iMode)
return false;
}
}
m_File = fopen(iFileName, Mode);
m_File = fopen(iFileName.c_str(), Mode);
return (m_File != NULL);
}

View File

@ -58,12 +58,12 @@ public:
cFile(void);
/// Constructs and opens / creates the file specified, use IsOpen() to check for success
cFile(const char * iFileName, EMode iMode);
cFile(const AString & iFileName, EMode iMode);
/// Auto-closes the file, if open
~cFile();
bool Open(const char * iFileName, EMode iMode);
bool Open(const AString & iFileName, EMode iMode);
void Close(void);
bool IsOpen(void) const;
bool IsEOF(void) const;

View File

@ -19,10 +19,18 @@ cHeartBeat::cHeartBeat()
Authenticate();
}
cHeartBeat::~cHeartBeat()
{
}
void cHeartBeat::ReceivedData( char a_Data[256], int a_Size )
{
if( a_Size < 0 ) // Disconnected
@ -97,28 +105,40 @@ void cHeartBeat::ReceivedData( char a_Data[256], int a_Size )
} while( bLoop );
}
void cHeartBeat::SendUpdate()
{
CloseSocket();
if( Connect( "mc-server.org", 80 ) )
{
int Port = cRoot::Get()->GetServer()->GetPort();
char c_Port[16];
sprintf_s( c_Port, 16, "%i", Port );
std::string sPort = std::string( c_Port );
std::string sChecksum = md5( m_ServerID + sPort );
SendMessage( (std::string("GET http://master.mc-server.org/?update=") + m_ServerID + std::string("&checksum=") + sChecksum + std::string("&port=") + sPort + "\n").c_str() );
AString Msg;
AString sPort;
Printf(sPort, "%i", Port);
AString sChecksum = md5( m_ServerID + sPort );
Printf(Msg, "GET http://master.mc-server.org/?update=%s&checksum=%s&port=%d\n", m_ServerID, sChecksum , Port);
SendMessage(Msg.c_str());
}
}
void cHeartBeat::Authenticate()
{
CloseSocket();
if( Connect( "mc-server.org", 80 ) )
if (Connect( "mc-server.org", 80))
{
m_State = 1;
int RetVal = SendMessage( "GET http://master.mc-server.org/\r\n\r\n");
LOGINFO("Returned %i", RetVal );
LOGINFO("Returned %i", RetVal);
}
}

View File

@ -13,7 +13,7 @@
// When in MSVC, the debugger provides "thread naming" by catching special exceptions. Interface here:
#ifdef _MSC_VER
#if defined(_MSC_VER) && defined(_DEBUG)
//
// Usage: SetThreadName (-1, "MainThread");
//
@ -41,7 +41,7 @@ static void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName)
{
}
}
#endif // _MSC_VER
#endif // _MSC_VER && _DEBUG

View File

@ -6,6 +6,7 @@
#include <fstream>
#include <ctime>
#include <stdarg.h>
#include "cMakeDir.h"
@ -13,35 +14,31 @@
cLog* cLog::s_Log = NULL;
cLog::cLog( const char* a_FileName )
cLog::cLog(const AString & a_FileName )
: m_File(NULL)
{
s_Log = this;
// create logs directory
#ifdef _WIN32
{
SECURITY_ATTRIBUTES Attrib;
Attrib.nLength = sizeof(SECURITY_ATTRIBUTES);
Attrib.lpSecurityDescriptor = NULL;
Attrib.bInheritHandle = false;
::CreateDirectory("logs", &Attrib);
}
#else
{
mkdir("logs", S_IRWXU | S_IRWXG | S_IRWXO);
}
#endif
cMakeDir::MakeDir("logs");
OpenLog( (std::string("logs/") + std::string(a_FileName)).c_str() );
OpenLog( (std::string("logs/") + a_FileName).c_str() );
}
cLog::~cLog()
{
CloseLog();
s_Log = NULL;
}
cLog* cLog::GetInstance()
{
if(s_Log)
@ -51,6 +48,10 @@ cLog* cLog::GetInstance()
return s_Log;
}
void cLog::CloseLog()
{
if( m_File )
@ -58,6 +59,10 @@ void cLog::CloseLog()
m_File = 0;
}
void cLog::OpenLog( const char* a_FileName )
{
if(m_File) fclose (m_File);
@ -68,9 +73,13 @@ void cLog::OpenLog( const char* a_FileName )
#endif
}
void cLog::ClearLog()
{
#ifdef _WIN32
#ifdef _WIN32
if( fopen_s( &m_File, "log.txt", "w" ) == 0)
fclose (m_File);
#else
@ -81,43 +90,43 @@ void cLog::ClearLog()
m_File = 0;
}
void cLog::Log(const char* a_Format, va_list argList )
{
char c_Buffer[1024];
if( argList != 0 )
{
vsnprintf_s(c_Buffer, 1024, 1024, a_Format, argList );
}
else
{
sprintf_s( c_Buffer, 1024, "%s", a_Format );
}
void cLog::Log(const char* a_Format, va_list argList)
{
AString Message;
AppendVPrintf(Message, a_Format, argList);
time_t rawtime;
time ( &rawtime );
#ifdef _WIN32
struct tm timeinfo;
localtime_s( &timeinfo, &rawtime );
#else
struct tm* timeinfo;
#ifdef _WIN32
struct tm timeinforeal;
timeinfo = &timeinforeal;
localtime_s(timeinfo, &rawtime );
#else
timeinfo = localtime( &rawtime );
#endif
char c_Buffer2[1024];
#ifdef _WIN32
sprintf_s(c_Buffer2, 1024, "[%02d:%02d:%02d] %s\n", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, c_Buffer);
#else
sprintf(c_Buffer2, "[%02d:%02d:%02d] %s\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, c_Buffer);
#endif
if(m_File){
fputs(c_Buffer2, m_File);
AString Line;
Printf(Line, "[%02d:%02d:%02d] %s\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, Message.c_str());
if (m_File)
{
fputs(Line.c_str(), m_File);
fflush(m_File);
}
printf("%s", c_Buffer2 );
printf("%s", Line.c_str());
}
void cLog::Log(const char* a_Format, ...)
{
va_list argList;
@ -126,7 +135,15 @@ void cLog::Log(const char* a_Format, ...)
va_end(argList);
}
void cLog::SimpleLog(const char* a_String)
{
Log("%s", a_String );
}

View File

@ -4,19 +4,21 @@
#include "FileDefine.h"
#ifndef _WIN32
#include <stdarg.h>
#include <stdarg.h>
#endif
class cLog { // tolua_export
class cLog
{ // tolua_export
private:
FILE* m_File;
static cLog* s_Log;
FILE * m_File;
static cLog * s_Log;
#ifdef _WIN32
typedef char* va_list;
#endif
public:
cLog( const char* a_FileName );
cLog(const AString & a_FileName);
~cLog();
void Log(const char* a_Format, va_list argList );
void Log(const char* a_Format, ...);
@ -28,3 +30,7 @@ public:
static cLog* GetInstance();
};
//tolua_end

View File

@ -16,17 +16,25 @@ cMCLogger* cMCLogger::GetInstance()
return s_MCLogger;
}
cMCLogger::cMCLogger()
{
m_CriticalSection = new cCriticalSection();
char c_Buffer[128];
sprintf_s(c_Buffer, 128, "LOG_%d.txt", (int)time(0) );
m_Log = new cLog(c_Buffer);
AString FileName;
Printf(FileName, "LOG_%d.txt", (int)time(0) );
m_Log = new cLog(FileName);
m_Log->Log("--- Started Log ---");
s_MCLogger = this;
}
cMCLogger::cMCLogger( char* a_File )
{
m_CriticalSection = new cCriticalSection();

View File

@ -784,8 +784,8 @@ bool cPlayer::LoadFromDisk()
if( itr->second ) LOGINFO("%s", itr->first.c_str() );
}
char SourceFile[128];
sprintf_s(SourceFile, 128, "players/%s.json", m_pState->PlayerName.c_str() );
AString SourceFile;
Printf(SourceFile, "players/%s.json", m_pState->PlayerName.c_str() );
cFile f;
if (!f.Open(SourceFile, cFile::fmRead))
@ -796,8 +796,8 @@ bool cPlayer::LoadFromDisk()
// Get file size
long FileSize = f.GetSize();
char * buffer = new char[FileSize];
if (f.Read(buffer, FileSize) != FileSize )
std::auto_ptr<char> buffer(new char[FileSize]);
if (f.Read(buffer.get(), FileSize) != FileSize)
{
LOGERROR("ERROR READING FROM FILE \"%s\"", SourceFile);
return false;
@ -806,12 +806,12 @@ bool cPlayer::LoadFromDisk()
Json::Value root;
Json::Reader reader;
if( !reader.parse( buffer, root, false ) )
if (!reader.parse(buffer.get(), root, false))
{
LOGERROR("ERROR WHILE PARSING JSON FROM FILE %s", SourceFile);
}
delete [] buffer;
buffer.reset();
Json::Value & JSON_PlayerPosition = root["position"];
if( JSON_PlayerPosition.size() == 3 )
@ -876,8 +876,8 @@ bool cPlayer::SaveToDisk()
Json::StyledWriter writer;
std::string JsonData = writer.write( root );
char SourceFile[128];
sprintf_s(SourceFile, 128, "players/%s.json", m_pState->PlayerName.c_str() );
AString SourceFile;
Printf(SourceFile, "players/%s.json", m_pState->PlayerName.c_str() );
cFile f;
if (!f.Open(SourceFile, cFile::fmWrite))

View File

@ -7,33 +7,33 @@
cSemaphore::cSemaphore( unsigned int a_MaxCount, unsigned int a_InitialCount /* = 0 */ )
#ifndef _WIN32
: m_bNamed( false )
: m_bNamed( false )
#endif
{
#ifndef _WIN32
(void)a_MaxCount;
m_Handle = new sem_t;
if( sem_init( (sem_t*)m_Handle, 0, 0 ) )
{
LOG("WARNING cSemaphore: Could not create unnamed semaphore, fallback to named.");
delete (sem_t*)m_Handle; // named semaphores return their own address
m_bNamed = true;
(void)a_MaxCount;
m_Handle = new sem_t;
if (sem_init( (sem_t*)m_Handle, 0, 0))
{
LOG("WARNING cSemaphore: Could not create unnamed semaphore, fallback to named.");
delete (sem_t*)m_Handle; // named semaphores return their own address
m_bNamed = true;
char c_Str[32];
sprintf( c_Str, "cSemaphore%p", this );
m_Handle = sem_open( c_Str, O_CREAT, 777, a_InitialCount );
if( m_Handle == SEM_FAILED )
{
LOG("ERROR: Could not create Semaphore. (%i)", errno );
}
else
{
if( sem_unlink( c_Str ) != 0 )
{
LOG("ERROR: Could not unlink cSemaphore. (%i)", errno);
}
}
}
AString Name;
Printf(Name, "cSemaphore%p", this );
m_Handle = sem_open(Name.c_str(), O_CREAT, 777, a_InitialCount);
if( m_Handle == SEM_FAILED )
{
LOG("ERROR: Could not create Semaphore. (%i)", errno );
}
else
{
if( sem_unlink( c_Str ) != 0 )
{
LOG("ERROR: Could not unlink cSemaphore. (%i)", errno);
}
}
}
#else
m_Handle = CreateSemaphore(
NULL, // security attribute

View File

@ -224,18 +224,18 @@ void cWebAdmin::Request_Handler(webserver::http_request* r)
}
else
{
char MemUsage[32];
sprintf( MemUsage, "%0.2f", ((double)resource_usage.ru_maxrss / 1024 / 1024) );
ReplaceString( Template, std::string("{MEM}"), MemUsage );
AString MemUsage;
Printf(MemUsage, "%0.2f", ((double)resource_usage.ru_maxrss / 1024 / 1024) );
ReplaceString(Template, std::string("{MEM}"), MemUsage);
}
#else
HANDLE hProcess = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc;
if( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc) ) )
{
char MemUsage[32];
sprintf( MemUsage, "%0.2f", (pmc.WorkingSetSize / 1024.f / 1024.f) );
ReplaceString( Template, std::string("{MEM}"), MemUsage );
AString MemUsage;
Printf(MemUsage, "%0.2f", (pmc.WorkingSetSize / 1024.f / 1024.f) );
ReplaceString( Template, "{MEM}", MemUsage );
}
#endif
// end mem usage