I'm actually programming and end to end encryped calendar. For this I am using cryptlib. I've more or less copied the code from the manual. But always, when I try to generate a root ca. It fails with error code -2 at cryptSignCert(). (Which means, according to the manual, that there is a problem with the second parameter) Here is a little code to reproduce the problem.
#include <iostream>
#include <cstring>
#include "cryptlib.h"
/*Generating a root ca*/
auto genRootCA(const char* commonName,const char* keyLabel,const char* country) -> int
{
int status;
CRYPT_CONTEXT cryptContext;
cryptCreateContext( &cryptContext, CRYPT_UNUSED, CRYPT_ALGO_RSA );
cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_LABEL, keyLabel, strlen( keyLabel ) );
cryptGenerateKey( cryptContext );
CRYPT_CERTIFICATE cryptCertificate;
cryptCreateCert(&cryptCertificate,CRYPT_UNUSED,CRYPT_CERTTYPE_CERTIFICATE);
cryptSetAttributeString(cryptCertificate,CRYPT_CERTINFO_COUNTRYNAME,country,strlen(country));
cryptSetAttributeString(cryptCertificate,CRYPT_CERTINFO_COMMONNAME,commonName,strlen(commonName));
//Set to self-signed
cryptSetAttribute(cryptCertificate,CRYPT_CERTINFO_SELFSIGNED,1);
cryptSetAttribute(cryptCertificate,CRYPT_CERTINFO_CA,1);
//Sign certificate
status = cryptSignCert(cryptCertificate,cryptContext); //This is, what is actually not working
if( cryptStatusError( status ) )
{
cryptDestroyContext( cryptContext );
cryptDestroyCert(cryptCertificate);
return( status );
}
//Save data to disk....(cut out)
}
int main()
{
cryptInit();
cryptAddRandom(NULL,CRYPT_RANDOM_FASTPOLL);
std::cout << "Generating root ca.\n";
int r = genRootCA("test#example.com","Private key","DE");
std::cout << "Returned value " << r << std::endl;
cryptEnd();
}
Thanks in advance,
David.
I've finally found a solution for the problem. I've forgotten to add the public key to the certificate. Here is a working example code:
#include <iostream>
#include <cstring>
#include "cryptlib.h"
/* generating the root ca */
auto genRootCA(const char* commonName,const char* keyLabel, const char* country,const char* path, const char* password) -> int
{
int status;
CRYPT_CONTEXT cryptContext;
cryptCreateContext( &cryptContext, CRYPT_UNUSED, CRYPT_ALGO_RSA );
cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_LABEL, keyLabel, strlen( keyLabel ) );
cryptGenerateKey( cryptContext );
CRYPT_CERTIFICATE cryptCertificate;
cryptCreateCert(&cryptCertificate,CRYPT_UNUSED,CRYPT_CERTTYPE_CERTIFICATE);
/* Add the public key */
status = cryptSetAttribute( cryptCertificate,
CRYPT_CERTINFO_SUBJECTPUBLICKEYINFO, cryptContext );
cryptSetAttributeString(cryptCertificate,CRYPT_CERTINFO_COUNTRYNAME,country,strlen(country));
cryptSetAttributeString(cryptCertificate,CRYPT_CERTINFO_COMMONNAME,commonName,strlen(commonName));
//Set to self-signed
cryptSetAttribute(cryptCertificate,CRYPT_CERTINFO_SELFSIGNED,1);
cryptSetAttribute(cryptCertificate,CRYPT_CERTINFO_CA,1);
//Sign certificate
status = cryptSignCert(cryptCertificate,cryptContext); //Works now
if( cryptStatusError( status ) )
{
cryptDestroyContext( cryptContext );
cryptDestroyCert(cryptCertificate);
return( status );
}
//Saving data to disk (cut out)
return CRYPT_OK;
}
int main()
{
cryptInit();
cryptAddRandom(NULL,CRYPT_RANDOM_FASTPOLL);
std::cout << "Generating root ca.\n";
int r = genRootCA("test#example.com","Private key","DE","key.pem","abc");
std::cout << "Returned value " << r << std::endl;
cryptEnd();
}
I hope this helps others, who have the same problem.
Related
how can I write to a file at the nth line (for example the 5th line) in c++?
here's my attempt:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream stream1("1.txt");
string line ;
ofstream stream2("2.txt");
int lineNumber = 0;
while(getline( stream1, line ) )
{
if (lineNumber == 5)
{
stream2 << "Input" << endl;
lineNumber = 0;
}
lineNumber++;
}
stream1.close();
stream2.close(); return 0;
}
in "1.txt", I have the word "Student" at the 4th line, now I want to ignore the above 4 lines and input the word "Input" at the 5th line (below the word "Student"). When I run the above code, the output file is blank. Any suggestion how to fix this? Thanks.
If I understand it right, all you want is a replica of 1.txt in 2.txt with just the specific line number replaced with your personal content.
In your case it seems, the word is "Input".
Well here is a code that I modified from your original one -
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream stream1("1.txt");
string line ;
ofstream stream2("2.txt");
int lineNumber = 0;
int line_to_replace = 4; //This will replace 5th line
while(getline( stream1, line ) )
{
if (lineNumber == line_to_replace)
{
stream2 << "Input" << endl;
}
else
stream2 << line << endl;
lineNumber++;
}
stream1.close();
stream2.close();
return 0;
}
Input File (1.txt) -
sdlfknas
sdfas
sdf
g
thtr
34t4
bfgndty
45y564
grtg
Output File (2.txt) -
sdlfknas
sdfas
sdf
g
Input
34t4
bfgndty
45y564
grtg
p.s. To learn and understand programming better, I would recommend not to use:
using namespace std;
When you're reading the 5th line, lineNumber equals 4 b/c you start your counting at 0.
Change if(lineNumber == 5)
to if(lineNumber == 4) You also have an issue where you're setting lineNumber = 0 then immediately incrementing to 1, so you're only going to count 4 lines before outputting again.
I would create a function like this...
bool isBlank(string line) {
if (!line.empty()) {
for (auto x: line) {
if (isalnum(x)) {
return false;
}
}
}
return true;
}
It returns true if a string is empty or has no alphanumeric characters.
You can call this function right after the getline statement.
The isalnum function is specified in <cctype>
After working with your code I managed to get the output that you desired. Here is the updated version of your code.
#include <iostream>
#include <fstream>
int main() {
std::ifstream stream1( "1.txt" );
std::string line;
std::ofstream stream2( "2.txt" );
int lineNumber = 1;
while ( getLine( stream1, line ) ) {
if ( lineNumber == 5 ) {
stream2 << "Input" << std::endl;
} else {
stream2 << std::endl;
lineNumber++;
}
}
stream1.close();
stream2.close();
return 0;
}
The one thing you have to make sure is that in your 1.txt that has the word student on the 4th line is that you must have at least 2 empty lines after this text in the file. A simple enter or carriage return will do! If you do not the while( getline() ) will go out of scope and it will not read the next line and the code block will never enter your if() statement when lineNumber == 5 and it will not print the text "Input" to your stream2 file stream object.
If your last line of text in your 1.txt file is the line with the string of text Student what happens here is it will add this line of text to your line string variable then the code will increment your lineNumber to equal 5. The next time you go into the while loop to call getline() it returns false because you are at the EOF since there are no more lines of text from the file to read in and this causes the while loop to break out of execution and it goes out of scope and the if( lineNumber == 5 ) never gets called because it is nested within the while loop's scope.
My first answer addressed the issue with your problem and getting the output to your text file appropriately. However as I mentioned about the while loop for reading in a line of text and using the same counter for both file streams is not very elegant. A more accurate way to do this which will also allow for debugging to be simplified would be to read in your full input file one line at a time and save each line into a string while storing your strings in a vector. This way you can parse each line of text that you need one at a time and you can easily traverse your vector to quickly find your line of text. You should also do checks to make sure your file exists and that it opens correctly.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
std::string strTextFileIn( "1.txt" );
std::ifstream in;
std::string strLine;
std::vector<std::string> vFileContents;
// Open File Stream
in.open( strTextFileIn.c_str(), std::ios_base::in );
// Test To Make Sure It Opened Properly And That It Exists
if ( !in.is_open() ) {
std::cout << "Failed to open file, check to make sure file exists." << std::endl;
return -1;
} else {
while ( !in.eof() ) {
// Get Line Of Text And Save To String
std::getline( in, strLine );
// Push String Into Vector
vFileContents.push_back( strLine );
}
}
// Done With File Close File Stream
if ( in.is_open() ) {
in.close();
}
// Now That We Have Read In The File Contents And Have Saved Each Line Of Text To A String
// And Stored It In Our Container (Vector) We Can Traverse Our Vector To Find Which String
// Matches The Text We Are Looking For Retrive Its Indexed Value And Then Write To Our
// Output File According To Where You Want The Text To Be Written
unsigned index = 0;
const std::string strLookup( "Student" );
for ( unsigned int i = 0; i < vFileContents.size(); i++ ) {
if ( vFileContents[i] == strLookup ) {
// Strings Match We Have Our Indexed Value
index = i;
}
}
// We Want To Write Our Line Of Text 1 Line Past Our Index Value As You Have Stated.
std::string strTextFileOut( "2.txt" );
std::ofstream out;
// Open Our File For Writting
out.open( strTextFileOut.c_str(), std::ios_base::out );
if ( !out.is_open() ) {
std::cout << "Failed To open file.";
vFileContents.clear();
return -1;
} else {
for ( unsigned int i = 1; i <= index; i++ ) {
out << std::endl; // Write Blank Lines
}
// The Text Or String You Want To Write To File
out << "Input" << std::endl;
}
// Done With File Stream
if ( in.is_open() ) {
in.close();
}
// Clear Out Vector
vFileContents.clear();
return 0;
} // main
Now this can be simplified a bit more by creating a class hierarchy for working with various file stream object types so that you don't have to write this code to open, close, check validity, read in full file or by line over and over again everywhere you need it. This makes it modular. However this structure relies on a few other classes such as an ExceptionHandler class and a Logger class. Below is a small multi file application.
stdafx.h NOTE: Not all of these includes and defines will be used here, but this is coming from a larger project of mine and I'm stripping out only the classes that are needed here, but leaving my standard header as is. The only contents that I stripped out of this "stdafx.h" is anything that has to deal with OpenGL, OpenAL, Ogg - Vorbis, GLM Libraries & APIs
#ifndef STDAFX_H
#define STDAFX_H
#define VC_EXTRALEAN // Exclude Rarely Used Stuff Windows Headers - Windows Only
// Instead of Creating Another File That VS Makes For You "targetver.h"
// I Will Just Append Its Contents Here
#include <SDKDDKVer.h> // Windows Only
#include <Windows.h> // Windows Only
#include <process.h>
#include <tchar.h>
#include <conio.h>
#include <memory>
#include <string>
#include <numeric>
#include <vector>
#include <array>
#include <unordered_map>
#include <queue>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <fstream>
#include "ExceptionHandler.h"
namespace pro {
enum ReturnCode {
RETURN_OK = 0,
RETURN_ERROR = 1,
};
extern const unsigned INVALID_UNSIGNED;
extern const unsigned INVALID_UNSIGNED_SHORT;
} // namespace pro
#endif // STDAFX_H
stdafx.cpp
#include "stdafx.h"
namespace pro {
const unsigned INVALID_UNSIGNED = static_cast<const unsigned>( -1 );
const unsigned INVALID_UNSIGNED_SHORT = static_cast<const unsigned short>( -1 );
} // namespace pro
ExceptionHandler.h
#ifndef EXCEPTION_HANDLER_H
#define EXCEPTION_HANDLER_H
namespace pro {
class ExceptionHandler sealed {
private:
std::string m_strMessage;
public:
explicit ExceptionHandler( const std::string& strMessage, bool bSaveInLog = true );
explicit ExceptionHandler( const std::ostringstream& strStreamMessage, bool bSavedInLog = true );
// ~ExceptionHandler(); // Default Okay
// ExeptionHandler( const ExceptionHandler& c ); // Default Copy Constructor Okay & Is Needed
const std::string& getMessage() const;
private:
ExceptionHandler& operator=( const ExceptionHandler& c ); // Not Implemented
}; // ExceptionHandler
} // namespace pro
#endif // EXCEPTION_HANDLER_H
ExceptionHandler.cpp
#include "stdafx.h"
#include "ExceptionHandler.h"
#include "Logger.h"
namespace pro {
ExceptionHandler::ExceptionHandler( const std::string& strMessage, bool bSaveInLog ) :
m_strMessage( strMessage ) {
if ( bSavedInLog ) {
Logger::log( m_strMessage, Logger::TYPE_ERROR );
}
}
ExceptionHandler::ExceptionHandler( const std::ostringstream& strStreamMessage, bool bSaveInLog ) :
m_strMessage( strStreamMessage.str() ) {
if ( bSaveInLog ) {
Logger::log( m_strMessage, Logger::TYPE_ERROR );
}
}
const std::string& ExceptionHandler::getMessage() const {
return m_strMessage;
}
} // namespace pro
BlockThread.h -- Needed For Logger
#ifndef BLOCK_THREAD_H
#define BLOCK_THREAD_H
namespace pro {
class BlockThread sealed {
private:
CRITICAL_SECTION* m_pCriticalSection;
public:
explicit BlockThread( CRITICAL_SECTION& criticalSection );
~BlockThread();
private:
BlockThread( const BlockThread& c ); // Not Implemented
BlockThread& operator=( const BlockThread& c ); // Not Implemented
}; // BlockThread
} // namespace pro
#endif // BLOCK_THREAD_H
BlockThread.cpp
#include "stdafx.h"
#include "BlockThread.h"
namespace pro {
BlockThread::BlockThread( CRTICAL_SECTION& criticalSection ) {
m_pCriticalSection = &criticalSection;
EnterCriticalSection( m_pCriticalSection );
}
BlockThread::~BlockThread() {
LeaveCriticalSection( m_pCriticalSection );
}
} // namespace pro
Logger is a Singleton since you will only want one instance of it while your application is running.
Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
namespace pro {
class Singleton {
public:
enum SingletonType {
TYPE_LOGGER = 0, // Must Be First!
// TYPE_SETTINGS,
// TYPE_ENGINE,
};
private:
SingletonType m_eType;
public:
virtual ~Singleton();
protected:
explicit Singleton( SingletonType eType );
void logMemoryAllocation( bool isAllocated ) const;
private:
Singleton( const Singleton& c ); // Not Implemented
Singleton& operator=( const Singleton& c ); // Not Implemented
}; // Singleton
} // namespace pro
#endif // SINGLETON_H
Singleton.cpp
#include "stdafx.h"
#include "Logger.h"
#include "Singleton.h"
//#include "Settings.h"
namespace pro {
struct SingletonInfo {
const std::string strSingletonName;
bool isConstructed;
SingletonInfo( const std::string& strSingletonNameIn ) :
strSingletonName( strSingletonNameIn ),
isConstructed( false ) {}
};
// Order Must Match Types Defined In Singleton::SingletonType enum
static std::array<SingletonInfo, 1> s_aSingletons = { SingletonInfo( "Logger" ) }; /*,
SingletonInfo( "Settings" ) };*/ // Make Sure The Number Of Types Matches The Number In This Array
Singleton::Singleton( SingletonType eType ) :
m_eType( eType ) {
bool bSaveInLog = s_aSingletons.at( TYPE_LOGGER ).isConstructed;
try {
if ( !s_aSingletons.at( eType ).isConstructed ) {
// Test Initialization Order
for ( int i = 0; i < eType; ++i ) {
if ( !s_aSingletons.at( i ).isConstructed ) {
throw ExceptionHandler( s_aSingletons.at( i ).strSingletonName + " must be constructed before constructing " + s_aSingletons.at( eType ).strSingletonName, bSaveInLog );
}
}
s_aSingletons.at( eType ).isConstructed = true;
/*if ( s_aSingletons.at( TYPE_ENGINE ).isConstructed &&
Setttings::get()->isDebugLogginEnabled( Settings::DEBUG_MEMORY ) ) {
logMemoryAllocation( true );
}*/
} else {
throw ExceptionHandler( s_aSingletons.at( eType ).strSingletonName + " can only be constructed once.", bSaveInLog );
}
} catch ( std::exception& ) {
// eType Is Out Of Range
std::ostringstream strStream;
strStream << __FUNCTION__ << " Invalid Singleton Type Specified: " << eType;
throw ExceptionHandler( strStream, bSaveInLog );
}
}
Singleton::~Singleton() {
/*if ( s_aSingletons.at( TYPE_ENGINE ).isConstructed &&
Settings::get()->isDebugLoggingEnabled( Settings::DEBUG_MEMORY ) ) {
logMemoryAllocation( false );
}*/
s_aSingletons.at( m_eType ).isConstructed = false;
}
void Singleton::logMemoryAllocation( bool isAllocated ) const {
if ( isAllocated ) {
Logger::log( "Created " + s_aSingletons.at( m_eType ).strSingletonName );
} else {
Logger::log( "Destroyed " + s_aSingletons.at( m_eType ).strSingletonName );
}
}
} // namespace pro
Logger.h
#ifndef LOGGER_H
#define LOGGER_H
#include "Singleton.h"
namespace pro {
class Logger sealed : public Singleton {
public:
// Number Of Items In Enum Type Must Match The Number
// Of Items And Order Of Items Stored In s_aLogTypes
enum LoggerType {
TYPE_INFO = 0,
TYPE_WARNING,
TYPE_ERROR,
TYPE_CONSOLE,
}; // LoggerType
private:
std::string m_strLogFilename;
unsigned m_uMaxCharacterLength;
std::array<std::string, 4> m_aLogTypes
const std::string m_strUnknownLogType;
HANDLE m_hConsoleOutput;
WORD m_consoleDefualtColor;
public:
explicit Logger( const std::string& strLogFilename );
virtual ~Logger();
static void log( const std::string& strText, LoggerType eLogType = TYPE_INFO );
static void log( const std::ostringstream& strStreamText, LoggerType eLogType = TYPE_INFO );
static void log( const char* szText, LoggerType eLogType = TYPE_INFO );
private:
Logger( const Logger& c ); // Not Implemented
Logger& operator=( const Logger& c ); // Not Implemented
}; // Logger
} // namespace pro
#endif // LOGGER_H
Logger.cpp
#include "stdafx.h"
#include "Logger.h"
#include "BlockThread.h"
#include "TextFileWriter.h"
namespace pro {
static Logger* s_pLogger = nullptr;
static CRITICAL_SECTION = s_criticalSection;
// White Text On Red Background
static const WORD WHITE_ON_RED = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED;
Logger::Logger( const std::string& strLogFilename ) :
Singleton( TYPE_LOGGER ),
m_strLogFilename( strLogFilename ),
m_uMaxCharacterLength( 0 ),
m_strUnknownLogType( "UNKNOWN" ) {
// Order Must Match Types Defined In Logger::Type enum
m_aLogTypes[0] = "Info";
m_aLogTypes[1] = "Warning";
m_aLogTypes[2] = "Error";
m_aLogTypes[3] = ""; // Console
// Find Widest Log Type String
m_uMaxCharacterLength = m_strUnknownLogType.size();
for each( const std::string& strLogType in m_aLogTypes ) {
if ( m_uMaxCharacterLength < strLogType.size() ) {
m_uMaxCharacterLength = strLogType.size();
}
}
InitializeCriticalSection( &s_criticalSection );
BlockThread blockThread( s_criticalSection ); // Enter Critical Section
// Start Log File
TextFileWriter file( m_strLogFilename, false, false );
// Prepare Console
m_hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );
CONSOLE_SCREEN_BUFFER consoleInfo;
GetConsoleScreenBufferInfo( m_hConsoleOutput, &consoleInfo );
m_consoleDefaultColor = consoleInfo.wAttributes;
s_pLogger = this;
logMemoryAllocation( true );
}
Logger::~Logger() {
logMemoryAllocation( false );
s_pLogger = nullptr;
DeleteCriticalSection( &s_criticalSection );
}
void Logger::log( const std::string& strtext, LoggerType eLogType ) {
log( strText.c_str(), eLogType );
}
void Logger::log( const std::string& strText, LoggerType eLogType ) {
log( strText.str().c_str(), eLogType );
}
void Logger::log( const char* szText, LoggerType eLogType ) {
if ( nullptr == s_pLogger ) {
std::cout << "Logger has not been initialized, can not log " << szText << std::endl;
return;
}
BlockThread blockThread( s_criticalSection ); // Enter Critical Section
std::ostringstream strStream;
// Default White Text On Red Background
WORD textColor = WHITE_ON_RED;
// Chose Log Type Text String, Display "UNKNOWN" If eLogType Is Out Of Range
strStream << std::setfill(' ') << std::setw( s_pLogger->m_uMaxCharacterLength );
try {
if ( TYPE_CONSOLE != eLogType ) {
strStream << s_pLogger->m_aLogTypes.at( eLogType );
}
if ( TYPE_WARNING == eLogType ) {
// Yellow
textColor = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN;
} else if ( TYPE_INFO == eLogType ) {
// Green
textColor = FOREGROUND_GREEN;
} else if ( TYPE_CONSOLE == eLogType ) {
// Cyan
textColor = FOREGROUND_GREEN | FOREGROUND_BLUE;
}
} catch( ... ) {
strStream << s_pLogger->m_strUnknownLogType;
}
// Date And Time
if ( TYPE_CONSOLE != eLogType ) {
SYSTEMTIME time;
GetLocalTime( &time );
strStream << " [" << time.wYear << "."
<< std::setfill('0') << std::setw( 2 ) << time.wMonth << "."
<< std::setfill('0') << std::setw( 2 ) << time.wDay << " "
<< std::setfill(' ') << std::setw( 2 ) << time.wHour << ":"
<< std::setfill('0') << std::setw( 2 ) << time.wMinute << ":"
<< std::setfill('0') << std::setw( 2 ) << time.wSecond << "."
<< std::setfill('0') << std::setw( 3 ) << time.wMilliseconds << "] ";
}
strStream << szText << std::endl;
// Log Message
SetConsoleTextAttribute( s_pLogger->m_hConsoleOutput, textColor );
std::cout << strStream.str();
// Save Message To Log File
try {
TextFileWriter file( s_pLogger->m_strLogFilename, true, false );
file.write( strStream.str() );
} catch( ... ) {
// Not Saved In Log File, Write Message To Console
std::cout << __FUNCTION__ << " failed to write to file: " << strStream.str() << std::endl;
}
// Reset To Default Color
SetConsoleTextAttribute( s_pLogger->m_hConsoleOutput, s_pLogger->m_consoleDefaultColor );
}
} // namespace pro
FileHandler.h - Base Class
#ifndef FILE_HANDLER_H
#define FILE_HANDLER_H
namespace pro {
// class AssetStorage; // Not Used Here
class FileHandler {
protected:
// static AssetStorage* m_pAssetStorage; // Not Used Here
std::fstream m_fileStream;
std::string m_strFilePath;
std::string m_strFilenameWithPath;
private:
bool m_bSaveExceptionInLog;
public:
virtual ~FileHandle();
protected:
FileHandler( const std::string& strFilename, bool bSaveExceptionInLog );
void throwError( const std::string& strMessage ) const;
void throwError( const std::ostringstream& strStreamMessage ) const;
bool getString( std::string& str, bool appendPath );
private:
FileHandler( const FileHandler& c ); // Not Implemented
FileHandler& operator=( const FileHandler& c ); // Not Implemented
}; // FileHandler
} // namespace pro
#endif // FILE_HANDLER_H
FileHandler.cpp
#include "stdafx.h"
#include "FileHandler.h"
// #include "AssetStorage.h" // Not Used Here
namespace pro {
// AssetStorage* FileHandler::m_pAssetStorage = nullptr; // Not Used Here
FileHandler::FileHandler( const std::string& strFilename, bool bSaveExceptionInLog ) :
m_bSaveExceptionInLog( bSaveExceptionInLog ),
m_strFilenameWithPath( strFilename ) {
/*if ( bSaveExceptionInLog && nullptr == m_pAssetStorage ) {
m_pAssetStorage = AssetStorage::get();
}*/ // Not Used Here
// Extract Path Info If It Exists
std::string::size_type lastIndex = strFilename.find_last_of( "/\\" );
if ( lastIndex != std::string::npos ) {
m_strFilePath = strFilename.substr( 0, lastIndex );
}
if ( strFilename.empty() ) {
throw ExceptionHandler( __FUNCTION__ + std::string( " missing filename", m_bSaveExceptionInLog );
}
}
FileHandler::~FileHandler() {
if ( m_fileStream.is_open() ) {
m_fileStream.close();
}
}
void FileHandler::throwError( const std::string& strMessage ) const {
throw ExceptionHandler( "File [" + m_strFilenameWithPath + "] " + strMessage, m_bSaveExceptionInLog );
}
void FileHandler::throwError( const std::ostringstream& strStreamMessage ) const {
throwError( strStreamMessage.str() );
}
bool FileHandler::getString( std::string& str, bool appendPath ) {
m_fileStream.read( &str[0], str.size() );
if ( m_fileStream.fail() ) {
return false;
}
// Trim Right
str.erase( str.find_first_of( char( 0 ) ) );
if ( appendPath && !m_strFilePath.empty() ) {
// Add Path If One Exists
str = m_strFilePath + "/" + str;
}
return true;
}
} // namespace pro
Now for the two inherited classes that you have been waiting for to handle File Streams. These Two are Strictly Text. Others within my project are TextureFiles, ModelObjectFiles, etc. I will be showing only the TextFileReader & TextFileWriter.
TextFileReader.h
#ifndef TEXT_FILE_READER_H
#define TEXT_FILE_READER_H
#include "FileHandler.h"
namespace pro {
class TextFileReader : public FileHandler {
private:
public:
explicit TextFileReader( const std::string& strFilename );
// virtual ~ TextFileReader(); // Default Okay
std::string readAll() const;
bool readLine( std::string& strLine );
private:
TextFileReader( const TextFileReader& c ); // Not Implemented
TextFileReader& operator=( const TextFileReader& c ); // Not Implemented
}; // TextFileReader
} // namespace pro
#endif // TEXT_FILE_READER_H
TextFileReader.cpp
#include "stdafx.h"
#include "TextFileReader.h"
namespace pro {
TextFileReader::TextFileReader( const std::string& strFilename ) :
FileHandler( strFilename, true ) {
m_fileStream.open( m_strFilenameWithPath.c_str(), std::ios_base::in );
if ( !m_fileStream.is_open() ) {
throwError( __FUNCTION__ + std::string( " can not open file for reading" ) );
}
std::string TextFileReader::readAll() const {
std::ostringstream strStream;
strStream << m_fileStream.rdbuf();
return strStream.str();
}
bool TextFileReader::readLine( std::string& strLine ) {
if ( m_fileStream.eof() ) {
return false;
}
std::getline( m_fileStream, strLine );
return true;
}
} // namespace pro
TextFileWriter.h
#ifndef TEXT_FILE_WRITER_H
#define TEXT_FILE_WRITER_H
#include "FileHandler.h"
namespace pro {
class TextFileWriter : public FileHandler {
private:
public:
TextFileWriter( const std::string& strFilename, bool bAppendToFile, bool bSaveExceptionInLog = true );
void write( const std::string& str );
private:
TextFileWriter( const TextFileWriter& c ); // Not Implemented
TextFileWriter& operator=( const TextFileWriter& c ); // Not Implemented
}; // TextFileWriter
} // namespace pro
#endif // TEXT_FILE_WRITER_H
TextFileWriter.cpp
#include "stdafx.h"
#include "TextFileWriter.h"
namespace pro {
TextFileWriter::TextFileWriter( const std::string& strFilename, bool bAppendToFile, bool bSaveExceptionInLog ) :
FileHandler( strFilename, bSaveExceptionInLog ) {
m_fileStream.open( m_strFilenameWithPath.c_str(),
std::ios_base::out | ( bAppendToFile ? std::ios_base::app : std::ios_base::trunc ) );
if ( !m_fileStream.is_open() ) {
throwError( __FUNCTION__ + std::string( " can not open file for writing" ) );
}
}
void TextFileWriter::write( const std::string& str ) {
m_fileStream << str;
}
} // namespace pro
Now to see a sample of this in action. If you look in the Logger class you will already see a use of the TextFileWriter.
main.cpp
#include "stdafx.h"
#include "Logger.h"
#include "TextFileReader.h"
#include "TextFileWriter.h"
int _tmain( int iNumArguments, _TCHAR* pArgumentText[] ) {
using namespace pro;
try {
// This Is Using The TextFileWriter & Console Output
// Logger::TYPE_INFO is by default!
Logger logger( "logger.txt" );
logger.log( "Some Info" );
logger.log( "Error!", Logger::TYPE_ERROR );
logger.log( "Warning!", Logger::TYPE_WARNING );
TextFileReader textReaderSingle( "logger.txt" );
TextFileReader textReaderAll( "logger.txt" );
std::string strTextSingle;
std::string strTextAll;
textReaderSingle.readLine( strTextSingle );
std::cout << "Read Single Line: << std::endl << strText << std::endl << std::endl;
strTextAll = textReaderAll.readAll();
std::cout << "Read All: " << std::endl << strTextAll << std::endl;
//Check The logger.txt that was generated in your projects folder!
std::cout << "Press any key to quit" << std::endl;
_getch();
} catch ( ExceptionHandler& e ) {
std::cout << "Exception Thrown: " << e.getMessage() << std::endl;
std::cout << "Press any key to quit" << std::endl;
_getch();
return RETURN_ERROR;
} catch( ... ) {
std::cout << __FUNCTION__ << " Caught Unknown Exception" << std::endl;
std::cout << "Press any key to quit" << std::endl;
_getch();
return RETURN_ERROR;
}
return RETURN_OK;
}
A majority of this work is accredited to Marek A. Krzeminski, MASc at www.MarekKnows.com. In essence all of these class objects are his; the only major difference is I used my own namespace pro as opposed to his. Both main functions are of my own work, the first stand alone and the second using his library code.
This is a project that has been in the works for a few years now and most of my advanced knowledge of the C++ language is due to following his video tutorials. This current project is a fairly large scale professional quality GameEngine using Shaders in OpenGL. All of this has been typed and debugged by hand while following along his tutorials.
As a major note; I had also hand typed a majority of this here as well, if this does not compile correctly it may be due to typographical errors. The source it self is a working application. What you see here is a very small percentage of his works! I am willing to accept the credit as to answer this person's question with the accumulation of this knowledge but I can not accept credit for this as being my own work in order to protect Marek and his copyright materials.
With this kind of setup it is quite easy to create your own file parsers and multiple file parsers for different types of files. As I stated above there are two other classes inherited from FileHandler that I did not show. If you would like to see more of this project, please vist www.MarekKnows.com and join the community.
I'm using dev c++, Wininet lib to download a file from web. I'm trying to change the referer or user agent. I use this code, it downloads successfully, but I don't know how to change http headers. Thanks.
#include <Windows.h>
#include <Wininet.h>
#include <iostream>
#include <fstream>
namespace {
::HINTERNET netstart ()
{
const ::HINTERNET handle =
::InternetOpenW(0, INTERNET_OPEN_TYPE_DIRECT, 0, 0, 0);
if ( handle == 0 )
{
const ::DWORD error = ::GetLastError();
std::cerr
<< "InternetOpen(): " << error << "."
<< std::endl;
}
return (handle);
}
void netclose ( ::HINTERNET object )
{
const ::BOOL result = ::InternetCloseHandle(object);
if ( result == FALSE )
{
const ::DWORD error = ::GetLastError();
std::cerr
<< "InternetClose(): " << error << "."
<< std::endl;
}
}
::HINTERNET netopen ( ::HINTERNET session, ::LPCWSTR url )
{
const ::HINTERNET handle =
::InternetOpenUrlW(session, url, 0, 0, 0, 0);
if ( handle == 0 )
{
const ::DWORD error = ::GetLastError();
std::cerr
<< "InternetOpenUrl(): " << error << "."
<< std::endl;
}
return (handle);
}
void netfetch ( ::HINTERNET istream, std::ostream& ostream )
{
static const ::DWORD SIZE = 1024;
::DWORD error = ERROR_SUCCESS;
::BYTE data[SIZE];
::DWORD size = 0;
do {
::BOOL result = ::InternetReadFile(istream, data, SIZE, &size);
if ( result == FALSE )
{
error = ::GetLastError();
std::cerr
<< "InternetReadFile(): " << error << "."
<< std::endl;
}
ostream.write((const char*)data, size);
}
while ((error == ERROR_SUCCESS) && (size > 0));
}
}
int main ( int, char ** )
{
const ::WCHAR URL[] = L"http://google.com";
const ::HINTERNET session = ::netstart();
if ( session != 0 )
{
const ::HINTERNET istream = ::netopen(session, URL);
if ( istream != 0 )
{
std::ofstream ostream("googleindex.html", std::ios::binary);
if ( ostream.is_open() ) {
::netfetch(istream, ostream);
}
else {
std::cerr << "Could not open 'googleindex.html'." << std::endl;
}
::netclose(istream);
}
::netclose(session);
}
}
#pragma comment ( lib, "Wininet.lib" )
You pass user agent string as the first parameter to InternetOpen
Use HttpOpenRequest and HttpSendRequest in place of InternetOpenUrl. Referer string is the 5th parameter to HttpOpenRequest
The third parameter of InternetOpenUrl is lpszHeaders [in] (from MSDN):
A pointer to a null-terminated string that specifies the headers to be sent to the HTTP server. For more information, see the description of the lpszHeaders parameter in the HttpSendRequest function.
You can set Referer and User agent like that:
LPWSTR headers = L"User-Agent: myagent\r\nReferer: my.referer.com\r\n\r\n\r\n";
//and then call
::InternetOpenUrlW(session, url, headers, -1, 0, 0);
You must separate every header with \r\n and close the block with \r\n\r\n
namespace Log {
#include <ctime>
#include <string>
#include <boost\scoped_ptr.hpp>
#ifndef LOG_PREPEND_TIMESTAMP_DEFAULT
#define LOG_PREPEND_TIMESTAMP_DEFAULT false
#endif
enum LogLevel_t { logFatal = 0, logError = 1, logWarning = 2, logVerbose = 3, logDebug = 4 };
std::string LogLevelToString( const LogLevel_t level ) {
static const char* const buffer[] = { "Fatal", "Error", "Warning", "Verbose", "Debug" };
return buffer[level];
}
class Log: public boost::noncopyable {
protected:
boost::scoped_ptr< std::ostringstream > Output_String;
bool m_Prepending_Timestamp;
size_t m_LinesOutputted;
public:
Log():
Output_String( new std::ostringstream ),
m_Prepending_Timestamp( LOG_PREPEND_TIMESTAMP_DEFAULT ),
m_LinesOutputted( 0 ) {}
void UsingTimestamp( bool Prepending_Timestamp = true ) {
m_Prepending_Timestamp = Prepending_Timestamp;
}
std::ostringstream& Get( const LogLevel_t level ) {
// Write line number
++m_LinesOutputted;
*Output_String << m_LinesOutputted << " | ";
if( m_Prepending_Timestamp == true ) {
//prepare a timestamp
time_t now = time( NULL );
std::string formatted_time( asctime( localtime( &now ) ) ); /* &now can be replaced with the above call when r-value references work (maybe) saving a stack var */
formatted_time.erase(( formatted_time.length( ) - 1 ), 1 ); /* Removes the \n(newline) that asctime adds for better formatting */
// Write timestamp to stream
*Output_String << formatted_time << " || ";
}
// Write Logging level(severity) to stream
*Output_String << LogLevelToString( level ) << " || ";
return *Output_String;
}
void Flush() {
*Output_String << std::endl;
fprintf( stdout, "%s", Output_String->str( ).c_str( ) );
fflush( stdout );
Output_String.reset( new std::ostringstream ); /* streams have lots of internal state clean streams are good */
}
~Log() {
*Output_String << std::endl;
fprintf( stdout, "%s", Output_String->str( ).c_str( ) );
fflush( stdout );
}
};
How would I implement a threshold without a macro?
If I wrap the body of get with a check I still have to return the stringstream.
I could change the return type to a pointer instead of a reference then return NULL but then every logger statement would have to have a null check for the returned stringstream
i need to print events on a folder with multiple subfolders. how to do it recursivly? Please print a c++ code. I am stucked!! Every time the evet is poped i need to open the subfolder, take the file and copy it into another directory. I don't want to list all the subfolders in every 2 seconds and find the files if there are any. Is not efficient. I need to use a monitor folder. Please help
The director that i want to monitor has multiple subfolders. Each subfolder has another subfolder that could contain in a moment of time a file. MainFolder->Subfolders->each subfolder-> subfolder -> file.
Here is the code I have for he moment:
/*
*/
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <sys/inotify.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
vector<string> SS;
void *print_message_function( void *ptr );
int main(int argc, char **argv ){
pthread_t t1;
int fd,fd1,wd,wd1,i=0,i1=0,len=0,len1=0;
int length;
char pathname[100],buf[1024],buf1[1024];
int data;
struct inotify_event *event;
char *message1 = "Thread 1";
FILE *fr;
// fd=inotify_init1(IN_NONBLOCK);//--rewrite
fd = inotify_init();
/* watch /test directory for any activity and report it back to me */
wd=inotify_add_watch(fd,"/home/MainFoder/",IN_ALL_EVENTS);
// int flag=0;
// char*ev="";
//wd=inotifytools_watch_recursively_with_exclude("/home/MainFolder/",IN_ALL_EVENTS);
while(1)
{
//sleep(30);
//read 1024 bytes of events from fd into buf
i=0;
len=read(fd,buf,1024);
while(i<len){
event=(struct inotify_event *) &buf[i];
/* watch /test directory for any activity and report it back to me */
/* check for changes */
{
if((event->mask & IN_OPEN) ||(event->mask & IN_CREATE))
{
printf("\n %s :was opened\n",event->name);
SS.push_back(event->name);
}
}
/* update index to start of next event */
i+=sizeof(struct inotify_event)+event->len;
}
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
wd1 = watch_from_filename(*ci);
}
/*
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
cout <<"HERE:"<< *cii << endl;
}
*/
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &t1, NULL, print_message_function, (void*) message1);
}
}
void *print_message_function( void *ptr )
{
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
cout <<"HERE:"<< *cii << endl;
std::string path=exec
}
}
This working sample on Github does what you're looking for: inotify-example.cpp
On CREATE events, the current wd (watch descriptor), plus the inotify_event wd and name components, are added to a Watch object (see sample).
The class includes methods to lookup wd and names in several ways.
This snippet shows how CREATE/DELETE events are handled:
if ( event->mask & IN_CREATE ) {
current_dir = watch.get(event->wd);
if ( event->mask & IN_ISDIR ) {
new_dir = current_dir + "/" + event->name;
wd = inotify_add_watch( fd, new_dir.c_str(), WATCH_FLAGS );
watch.insert( event->wd, event->name, wd );
total_dir_events++;
printf( "New directory %s created.\n", new_dir.c_str() );
} else {
total_file_events++;
printf( "New file %s/%s created.\n", current_dir.c_str(), event->name );
}
} else if ( event->mask & IN_DELETE ) {
if ( event->mask & IN_ISDIR ) {
new_dir = watch.erase( event->wd, event->name, &wd );
inotify_rm_watch( fd, wd );
total_dir_events--;
printf( "Directory %s deleted.\n", new_dir.c_str() );
} else {
current_dir = watch.get(event->wd);
total_file_events--;
printf( "File %s/%s deleted.\n", current_dir.c_str(), event->name );
}
}
You can do it in two steps:
Detect all the changes you're interested in on the root directory, plus (if not already included) creations (IN_CREATE).
If the creation is a directory, do the whole algorithm on it.
I have written the code for you. Now, you have to do only one change in this code. Just give path of your directory in main function.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <limits.h>
#include<sys/stat.h>
#include<dirent.h>
#include<time.h>
#include<string.h>
#include<unistd.h>
#define MAX_EVENTS 1024 /*Max. number of events to process at one go*/
#define LEN_NAME 16 /*Assuming that the length of the filename won't exceed 16 bytes*/
#define EVENT_SIZE ( sizeof (struct inotify_event) ) /*size of one event*/
#define BUF_LEN ( MAX_EVENTS * ( EVENT_SIZE + LEN_NAME )) /*buffer to store the data of events*/
void monitor(char *);
int evnt_mon(char *);
void main()
{
if(fork()==0)
evnt_mon("./usssb");// give path of your directory which you want to monitor
monitor("./usssb");// give path of your directory which you want to monitor
while(1);
}
void monitor(char * rt_dir)
{
struct stat st;
DIR *dirp;
struct dirent *dp;
char str[100][100]={ };
char temp[100];
char str1[500]=" ";
int i=0,j=0,src_ret=9,src_ret1=9;
strcpy(str1,rt_dir);
dirp=opendir(str1);
if(dirp==NULL)
{
perror("opendir");
return;
}
while(1)
{
dp=readdir(dirp);
if(dp==NULL)
break;
if((strcmp(dp->d_name,".\0")==0) || (strcmp(dp->d_name,"..")==0))
continue;
if((dp->d_type==DT_DIR)&&((strcmp(dp->d_name,".")!=0)&&(strcmp(dp->d_name,"..")!=0)))
{
strcat(str[i],str1);
strcat(str[i],"/");
strcat(str[i],dp->d_name);
if(fork()==0)
{
evnt_mon(str[i]);
}
i++;
}
}
closedir(dirp);
if(i>0)
{
for(j=0;j<i;j++)
{
monitor(str[j]);
}
}
}
int evnt_mon(char *argv)
{
int length, i = 0, wd;
int fd;
char buffer[BUF_LEN];
/* Initialize Inotify*/
fd = inotify_init();
if ( fd < 0 )
{
perror( "Couldn't initialize inotify");
}
/* add watch to starting directory */
wd = inotify_add_watch(fd, argv, IN_CREATE | IN_MODIFY | IN_DELETE);
if (wd == -1)
{
printf("Couldn't add watch to %s\n",argv);
}
else
{
printf("Watching:: %s\n",argv);
}
/* do it forever*/
while(1)
{
i = 0;
length = read( fd, buffer, BUF_LEN );
if ( length < 0 )
{
perror( "read" );
}
while ( i < length )
{
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
if ( event->len )
{
if ( event->mask & IN_CREATE)
{
if (event->mask & IN_ISDIR)
{
printf( "The directory %s was Created in %s.\n", event->name,argv );
if(fork()==0)
{
char p[100]=" ";
strcpy(p,argv);
strcat(p,"/");
strcat(p,event->name);
evnt_mon(p);
}
}
else
printf( "The file %s was Created with WD %d\n", event->name, event->wd );
}
if ( event->mask & IN_MODIFY)
{
if (event->mask & IN_ISDIR)
printf( "The directory %s was modified.\n", event->name );
else
printf( "The file %s was modified with WD %d\n", event->name, event->wd );
}
if ( event->mask & IN_DELETE)
{
if (event->mask & IN_ISDIR)
printf( "The directory %s was deleted from %s.\n", event->name,argv );
else
printf( "The file %s was deleted with WD %d\n", event->name, event->wd );
}
i += EVENT_SIZE + event->len;
}
}
}
/* Clean up*/
inotify_rm_watch( fd, wd );
close( fd );
return 0;
}
You might use the fanotify API. It allows you to monitor a complete mount. The only drawback is that you need to be root.
To address the problem stated by ribram (the 'hole':)). one possible solution i can think of is that we can do a combination of 'polling the directory' and 'using inotify'... i.e. Each time a directory is detected (directory only, don't do it for files):
add a watchpoint for the newly detected directory to inotify
'poll' (or 'scan') the newly detected directory (man readdir()) to see if there're already items (files, directories) created. Those are possibly the ones that are missing.
Note that to build an 'air-tight' case, the above steps' order is important. you need to add the watchpoint first than scan ... This will guarantee that an item is picked up by either 'scan' or inotify or both. In that case you may also need to aware of the dups. i.e. the same item can be both yielded by the scan and the inotify
EDIT
I've made changes to what I saw below and this is what I have
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string>
#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <errno.h>
using namespace std;
string buffer;
vector<string> ex;
int s;
void recvline ( int s, string* buf ) {
char in, t;
while ( 1 ) {
recv ( s, &in, 1, 0 );
*buf += in;
if ( in == 10 ) {
t = 1; }
if ( t && in == 13 ) {
break; }
}
}
void push ( int s, string msg ) {
string o = msg + "\r\n";
cout << "SENT:", o;
send ( s, o.c_str(), o.size(), 0 );
}
int main ( int argc, char *argv[] ) {
if ( argc < 3 ) {
cout << "Insufficient Arguments" << endl;
exit ( 7 ); }
s = socket ( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( s < 0 )
exit ( 1 );
struct hostent h = *gethostbyname ( argv[1] );
struct sockaddr_in c;
c.sin_family = AF_INET;
c.sin_port = htons(atoi(argv[2]));
c.sin_addr.s_addr = inet_addr ( h.h_addr_list[0] );
if ( connect ( s, (struct sockaddr*)&c, sizeof c ) != 0 ) {
cout << "Unable to connect to network" << endl;
cout << strerror(errno) << endl;
exit ( 2 );
}
push ( s, "USER LOLwat Lw lol.wat :LOLwat" );
push ( s, "NICK LOLwat" );
while ( true ) {
recvline ( s, &buffer );
cout << buffer;
if ( buffer.substr(0,4).c_str() == "PING" )
push ( s, "PONG " + buffer.substr(6,-2) );
}
}
And this is the result:
[dbdii407#xpcd Desktop]$ g++ ?.cpp -o 4096 -
[dbdii407#xpcd Desktop]$ ./4096 irc.scrapirc.com 6667 - Unable to connect to network - Network is unreachable
I think the problem is that this line:
c.sin_port = htons(*argv[2]);
Is not doing what you think it's doing. argv[2] is a string, *argv[2] is the first character of the string. So if you passed "4567" as the second command-line argument, then *argv[2] will be '4' which has ASCII value 52. That means you'll be attempting to connect to port 52, not "4567" as you would expect.
Change the line to:
c.sin_port = htons(atoi(argv[2]));
The atoi function takes a string and converts it to an integer. So "4567" would become 4567.
Also, in general, you should check the value of errno when a function call like that fails (it'll usually tell you in the documentation whether errno is set and the possible values it can be set to). That should help to give you some clue in the future.
Edit
As others have noted, make sure you pay attention to your braces. It's usually easier if you just always use braces around if, while, and so on. That is, this:
if ( connect ( s, (struct sockaddr*)&c, sizeof c ) != 0 )
cout << "Unable to connect to network" << endl;
exit ( 2 );
Is completely different to this:
if ( connect ( s, (struct sockaddr*)&c, sizeof c ) != 0 ) {
cout << "Unable to connect to network" << endl;
exit ( 2 );
}
I decided to completely redo my answer, in part due to the following comment in the gethostbyname manpage:
The gethostbyname*() and
gethostbyaddr*() functions are
obsolete. Applications should use
getaddrinfo(3) and getnameinfo(3)
instead.
Here is the reworked program ( cleaned up a bit with bcpp ) based on using getaddrinfo. I would strongly suggest always compiling with the following options:
g++ -Wall -Wextra irc.cpp -o irc
This showed up the following bugs in your code:
irc.cpp: In function ‘void push(int, std::string)’:
irc.cpp:40: warning: right-hand operand of comma has no effect
irc.cpp: In function ‘int main(int, char**)’:
irc.cpp:87: warning: comparison with string literal results in unspecified behaviour
I went ahead and fixed the errors. Also, try and eliminate global variables as much as possible.
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string>
#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <errno.h>
using namespace std;
string buffer;
vector<string> ex;
void recvline ( int s, string* buf )
{
char in, t;
while ( 1 )
{
recv ( s, &in, 1, 0 );
*buf += in;
if ( in == 10 )
{
t = 1;
}
if ( t && in == 13 )
{
break;
}
}
}
void push ( int s, string msg )
{
string o = msg + "\r\n";
cout << "SENT:" << o;
send ( s, o.c_str(), o.size(), 0 );
}
int main ( int argc, char *argv[] )
{
if ( argc < 3 )
{
cout << "Insufficient Arguments" << endl;
exit ( 7 );
}
int s, sfd;
struct addrinfo *result, *rp;
s = getaddrinfo(argv[1], argv[2], NULL, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (sfd == -1)
continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(sfd);
}
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(result); /* No longer needed */
push ( sfd, "USER LOLwat Lw lol.wat :LOLwat" );
push ( sfd, "NICK LOLwat" );
while ( true )
{
recvline ( sfd, &buffer );
cout << buffer;
if ( buffer.substr(0,4) == "PING" )
push ( sfd, "PONG " + buffer.substr(6,-2) );
}
}