What is the best way in C++03 to split a command line in to two strings: executable and arguments?
For example:
"\"c:\\Program Files\\MyFile.exe\" /a /b /c" => "c:\Program Files\MyFile.exe", "/a /b /c"
"c:\\Foo\\bar.exe -t \"myfile.txt\"" => "c:\Foo\bar.exe", "-t \"myfile.txt\""
"baz.exe \"quantum conundrum\"" => "baz.exe", "\"quantum conundrum\""
A good solution should handle both quotes and spaces.
boost is acceptable.
My current (working) solution:
void split_cmd( const std::string& cmd,
std::string* executable,
std::string* parameters )
{
std::string c( cmd );
size_t exec_end;
boost::trim_all( c );
if( c[ 0 ] == '\"' )
{
exec_end = c.find_first_of( '\"', 1 );
if( std::string::npos != exec_end )
{
*executable = c.substr( 1, exec_end - 1 );
*parameters = c.substr( exec_end + 1 );
}
else
{
*executable = c.substr( 1, exec_end );
std::string().swap( *parameters );
}
}
else
{
exec_end = c.find_first_of( ' ', 0 );
if( std::string::npos != exec_end )
{
*executable = c.substr( 0, exec_end );
*parameters = c.substr( exec_end + 1 );
}
else
{
*executable = c.substr( 0, exec_end );
std::string().swap( *parameters );
}
}
}
Related
so, I encountered a little problem and I am kinda stuck.
Basically I am trying to pass the value of a string** in C-type form to a char* string
The code is as follows:
static int BuildDBListSql( std::string **SqlBuf,
const char* ColumnNames,
const char* TableNames,
const char* CmdText,
sUINT Mode)
{
int rtnval = sSUCCESS;
const char * testSql = ( Mode & 02 ) ? ColumnNames : CmdText;
if ( SU_DbControl::DbCreateTradeTempTables(testSql) != sSUCCESS )
{
sLogMessage("Problem with temporary table results", sLOG_ERROR, 0);
return( sERROR );
}
if ( Mode & 02 )
{
*SqlBuf = new std::string[strlen(ColumnNames) + SQL_MAX_SELECT*40];
*SqlBuf = &std::string(ColumnNames);
if ( !( Mode & 010 ) )
{
// Attach State/Retrieval SQL.
char* SqlBufcopy = (*SqlBuf)->c_str();
sSQLInsertStateAndRetrieval( sDbConvertMode( Mode ), SqlBufcopy);
}
}
// SQL fragments are being passed:
else
{
size_t sqlBufLength = 0;
if ( Mode & 010 )
{
sqlBufLength = strlen(ColumnNames) + strlen(TableNames) + strlen(CmdText) + SQL_MAX_SELECT;
*SqlBuf = new std::string[ sqlBufLength ];
//sprintf( *SqlBuf, "SELECT %s FROM %s %s ",
*SqlBuf = fmt::format("SELECT {} FROM {} {} ", ColumnNames, TableNames, CmdText); // ColumnNames, TableNames, CmdText );
}
else
{
std::string *sqlPtr = new char[strlen(CmdText) + 2*SQL_MAX_SELECT];
strcpy( sqlPtr, CmdText );
sSQLSpecializeWhereClause( TableNames, sqlPtr );
sqlBufLength = strlen(ColumnNames) + strlen(TableNames) + SQL_MAX_SELECT;
sqlBufLength += strchr(TableNames, ',') ? strlen(CmdText) : strlen(sqlPtr);
*SqlBuf = new char[ sqlBufLength ];
sprintf( *SqlBuf, "SELECT %s From %s %s",
ColumnNames,
TableNames,
strchr( TableNames, ',' ) ? CmdText : sqlPtr );
delete [] sqlPtr;
// Attach State/Retrieval SQL
rtnval = sSQLInsertStateAndRetrieval( sDbConvertMode( Mode ),
*SqlBuf );
}
}
if (Mode & 0100)
{
char * tempBuf = sEntitySQLToDbSQL(*SqlBuf);
if( tempBuf )
{
delete [] *SqlBuf;
*SqlBuf = new char[ strlen(tempBuf) + 1];
strcpy(*SqlBuf, tempBuf);
}
else
{
sLogMessage("Error in sEntitySQLToDbSQL", sLOG_ERROR, 0);
return( sERROR );
}
}
return rtnval;
}
i get this error when running the solution: related to this line of code char* SqlBufcopy = (*SqlBuf)->c_str();
left of '.c_str' must have class/struct/union, type is std::string**
I kinda understand that the error is there due to me trying to get a c-type string out of a pointer, but I dont know the correct syntax to do what i want to do.
I tried with
char *SqlBufcopy = *SqlBuf.c_str()
also with
char *SqlBufcopy = *SqlBuf->c_str()
and it didnt work, help pls
To fix the error you ask about, change char *SqlBufcopy = *SqlBuf.c_str(); to
char *SqlBufcopy = (*SqlBuf)->c_str();
Reason: SqlBuf is pointer to pointer (which makes no sense at all), so to get to the actual object, you need to dereference it twice.
I use the example Plugin.cpp from amibroker ADK. I make a directory 'ASCII' under the folder 'amibroker' and put all the data inside named *.AQI. But no data found in amibroker. Is there something I changed in function GetQuotesEx cause the problem?
PLUGINAPI int GetQuotesEx( LPCTSTR pszTicker, int nPeriodicity, int nLastValid, int nSize, struct Quotation *pQuotes, GQEContext *pContext )
{
char filename[256];
FILE* fh;
int iLines = 0;
// format path to the file (we are using relative path)
sprintf_s(filename, "ASCII\\%s.AQI", pszTicker);
// open file for reading
fopen_s(&fh, filename, "r");
// if file is successfully opened read it and fill quotation array
if (fh)
{
char line[ 256 ];
// read the line of text until the end of text
// but not more than array size provided by AmiBroker
while( fgets( line, sizeof( line ), fh ) && iLines < nSize )
{
// get array entry
struct Quotation *qt = &pQuotes[ iLines ];
char* pTmp = NULL;
// parse line contents: divide tokens separated by comma (strtok) and interpret values
// date and time first
int datenum = atoi( strtok_s( line, ",", &pTmp) ); // YYMMDD
int timenum = atoi( strtok_s( NULL, ",", &pTmp) ); // HHMM
// unpack datenum and timenum and store date/time
qt->DateTime.Date = 0; // make sure that date structure is intialized with zero
qt->DateTime.PackDate.Minute = timenum % 100;
qt->DateTime.PackDate.Hour = timenum / 100;
qt->DateTime.PackDate.Year = 2000 + datenum / 10000;
qt->DateTime.PackDate.Month = ( datenum / 100 ) % 100;
qt->DateTime.PackDate.Day = datenum % 100;
// now OHLC price fields
qt->Open = (float) atof( strtok_s( NULL, ",", &pTmp) );
qt->High = (float) atof( strtok_s( NULL, ",", &pTmp) );
qt->Low = (float) atof( strtok_s( NULL, ",", &pTmp) );
qt->Price = (float) atof( strtok_s( NULL, ",", &pTmp) ); // close price
// ... and Volume
qt->Volume = (float) atof( strtok_s( NULL, ",\n", &pTmp) );
iLines++;
}
// close the file once we are done
fclose( fh );
}
// return number of lines read which is equal to
// number of quotes
return iLines;
}
I've been following Kamran Bigdely-Shamloo's article on how to get positional information from the HTC Vive and it has worked well so far. My next step was to "listen" to button presses. I've read the documentation and it says here that all I need to do is query IVRSystem::GetControllerStateand it'll return a
"struct with the current state of the controller"
This struct however always contains variables that have the 0 value. The following function is called in a while (true) loop from the main function.
bool CMainApplication::HandleInput()
{
SDL_Event sdlEvent;
bool bRet = false;
while ( SDL_PollEvent( &sdlEvent ) != 0 )
{
if ( sdlEvent.type == SDL_QUIT )
{
bRet = true;
}
else if ( sdlEvent.type == SDL_KEYDOWN )
{
if ( sdlEvent.key.keysym.sym == SDLK_ESCAPE
|| sdlEvent.key.keysym.sym == SDLK_q )
{
bRet = true;
}
if( sdlEvent.key.keysym.sym == SDLK_c )
{
m_bShowCubes = !m_bShowCubes;
}
}
}
// Process SteamVR events
// Periodically returns an event of type 404 ("VREvent_SceneApplicationChanged = 404, // data is process - The App actually drawing the scene changed (usually to or from the compositor)"
vr::VREvent_t event;
vr::VREvent_Controller_t controllerEvent;
std::chrono::milliseconds ms4;
while( m_pHMD->PollNextEvent( &event, sizeof( event ) ) )
{
ms4 = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
);
ProcessVREvent( &event);
printPositionalData(&event, ms4);
}
vr::VRControllerState_t state;
// Check every device attached, usually it's four devices
// Second if statement is never reached
for (int i = 0; i < 1000; i++) {
if (m_pHMD->GetControllerState(i, &state, sizeof(state))) {
dprintf("%d", i);
if (state.ulButtonPressed != 0 || state.unPacketNum != 0 || state.ulButtonTouched != 0) {
dprintf("Some action?");
}
}
}
dprintf("\n");
// Process SteamVR action state
// UpdateActionState is called each frame to update the state of the actions themselves. The application
// controls which action sets are active with the provided array of VRActiveActionSet_t structs.
vr::VRActiveActionSet_t actionSet = { 0 };
actionSet.ulActionSet = m_actionsetDemo;
vr::VRInput()->UpdateActionState( &actionSet, sizeof(actionSet), 1 );
m_bShowCubes = !GetDigitalActionState( m_actionHideCubes );
vr::VRInputValueHandle_t ulHapticDevice;
if ( GetDigitalActionRisingEdge( m_actionTriggerHaptic, &ulHapticDevice ) )
{
if ( ulHapticDevice == m_rHand[Left].m_source )
{
vr::VRInput()->TriggerHapticVibrationAction( m_rHand[Left].m_actionHaptic, 0, 1, 4.f, 1.0f, vr::k_ulInvalidInputValueHandle );
}
if ( ulHapticDevice == m_rHand[Right].m_source )
{
vr::VRInput()->TriggerHapticVibrationAction( m_rHand[Right].m_actionHaptic, 0, 1, 4.f, 1.0f, vr::k_ulInvalidInputValueHandle );
}
}
vr::InputAnalogActionData_t analogData;
if ( vr::VRInput()->GetAnalogActionData( m_actionAnalongInput, &analogData, sizeof( analogData ), vr::k_ulInvalidInputValueHandle ) == vr::VRInputError_None && analogData.bActive )
{
m_vAnalogValue[0] = analogData.x;
m_vAnalogValue[1] = analogData.y;
}
m_rHand[Left].m_bShowController = true;
m_rHand[Right].m_bShowController = true;
vr::VRInputValueHandle_t ulHideDevice;
if ( GetDigitalActionState( m_actionHideThisController, &ulHideDevice ) )
{
if ( ulHideDevice == m_rHand[Left].m_source )
{
m_rHand[Left].m_bShowController = false;
}
if ( ulHideDevice == m_rHand[Right].m_source )
{
m_rHand[Right].m_bShowController = false;
}
}
for ( EHand eHand = Left; eHand <= Right; ((int&)eHand)++ )
{
vr::InputPoseActionData_t poseData;
if ( vr::VRInput()->GetPoseActionData( m_rHand[eHand].m_actionPose, vr::TrackingUniverseStanding, 0, &poseData, sizeof( poseData ), vr::k_ulInvalidInputValueHandle ) != vr::VRInputError_None
|| !poseData.bActive || !poseData.pose.bPoseIsValid )
{
m_rHand[eHand].m_bShowController = false;
}
else
{
m_rHand[eHand].m_rmat4Pose = ConvertSteamVRMatrixToMatrix4( poseData.pose.mDeviceToAbsoluteTracking );
vr::InputOriginInfo_t originInfo;
if ( vr::VRInput()->GetOriginTrackedDeviceInfo( poseData.activeOrigin, &originInfo, sizeof( originInfo ) ) == vr::VRInputError_None
&& originInfo.trackedDeviceIndex != vr::k_unTrackedDeviceIndexInvalid )
{
std::string sRenderModelName = GetTrackedDeviceString( originInfo.trackedDeviceIndex, vr::Prop_RenderModelName_String );
if ( sRenderModelName != m_rHand[eHand].m_sRenderModelName )
{
m_rHand[eHand].m_pRenderModel = FindOrLoadRenderModel( sRenderModelName.c_str() );
m_rHand[eHand].m_sRenderModelName = sRenderModelName;
}
}
}
}
return bRet;
m_pHMD is initalized as follows:
vr::IVRSystem *m_pHMD;
....
m_pHMD = vr::VR_Init( &eError, vr::VRApplication_Background );
I must be doing something wrong because in the following snippet, the if statement is passed only for the first four iterations, which should be a controller, the vive tracker, the headset and the lighthouses. This tells me that I am able to access these states, but I am somehow not able to read the information.
for (int i = 0; i < 1000; i++) {
if (m_pHMD->GetControllerState(i, &state, sizeof(state))) {
dprintf("%d", i);
if (state.ulButtonPressed != 0 || state.unPacketNum != 0 || state.ulButtonTouched != 0) {
dprintf("Some action?");
}
}
I can't imagine its a bug, so my guess is that my configuration is faulty, or I'm doing the wrong query.
Any help is greatly appreciated!
Apparently I was making two mistakes.
Mistake #1 was that I was using the wrong sample file. I used hellovr_opengl from the OpenVr sample folder, but instead hellovr_dx12 was the working solution. It must have a different kind of configration as well, since I copied a function which was working into the hellovr_opengl project and there, it did not work! Then I copied the functions I added to the hellovr_dx12 project and was able to get the controller states of the Vive controller.
However, I wanted to get the states of the Vive Tracker, which didn't work. After some googling I found out about an issue with the current SteamVR driver, so I reverted it back to a beta hoftix, which solved the Vive Tracker issue for me.
You have to call;
vr::VRInput()->SetActionManifestPath
I have a weird error when trying to execute mysql_stmt_execute.
The flow goes:
I get the list of the tables in my database I am connecting. (catalog, schema and name)
For every table I'm getting the list of foreign keys, fields and indexes.
Everything goes good until I hit the table named performance_schema.events_stages_summary_by_account_by_event_name.
I get the error: Identifier name "events_stages_summary_by_account_by_event_name" is too long. The weird thing is that the name is not an identifier - it is a parameter to the query and it is less than 64 characters which is the identifier limit.
Below is the relevant code:
std::wstring query3 = L"SELECT kcu.column_name, kcu.ordinal_position, kcu.referenced_table_schema, kcu.referenced_table_name, kcu.referenced_column_name, rc.update_rule, rc.delete_rule FROM information_schema.key_column_usage kcu, information_schema.referential_constraints rc WHERE kcu.constraint_name = rc.constraint_name AND kcu.table_catalog = ? AND kcu.table_schema = ? AND kcu.table_name = ?;";
char *catalog_name = row[0] ? row[0] : NULL;
char *schema_name = row[1] ? row[1] : NULL;
char *table_name = row[2] ? row[2] : NULL;
MYSQL_BIND params[3];
unsigned long str_length1, str_length2, str_length3;
str_length1 = strlen( catalog_name ) * 2;
str_length2 = strlen( schema_name ) * 2;
str_length3 = strlen( table_name ) * 2;
str_data1 = new char[str_length1], str_data2 = new char[str_length2], str_data3 = new char[str_length3];
memset( str_data1, '\0', str_length1 );
memset( str_data2, '\0', str_length2 );
memset( str_data3, '\0', str_length3 );
memset( params, 0, sizeof( params ) );
strncpy( str_data1, catalog_name, str_length1 );
strncpy( str_data2, schema_name, str_length2 );
strncpy( str_data3, table_name, str_length3 );
params[0].buffer_type = MYSQL_TYPE_STRING;
params[0].buffer = (char *) str_data1;
params[0].buffer_length = strlen( str_data1 );
params[0].is_null = 0;
params[0].length = &str_length1;
params[1].buffer_type = MYSQL_TYPE_STRING;
params[1].buffer = (char *) str_data2;
params[1].buffer_length = strlen( str_data2 );
params[1].is_null = 0;
params[1].length = &str_length2;
params[2].buffer_type = MYSQL_TYPE_STRING;
params[2].buffer = (char *) str_data3;
params[2].buffer_length = strlen( str_data3 );
params[2].is_null = 0;
params[2].length = &str_length3;
if( mysql_stmt_bind_param( res1, params ) )
{
std::wstring err = m_pimpl->m_myconv.from_bytes( mysql_stmt_error( res1 ) );
errorMsg.push_back( err );
result = 1;
break;
}
else
{
prepare_meta_result = mysql_stmt_result_metadata( res1 );
if( !prepare_meta_result )
{
std::wstring err = m_pimpl->m_myconv.from_bytes( mysql_stmt_error( res1 ) );
errorMsg.push_back( err );
result = 1;
break;
}
else
{
if( mysql_stmt_execute( res1 ) )
{
std::wstring err = m_pimpl->m_myconv.from_bytes( mysql_stmt_error( res1 ) );
errorMsg.push_back( err );
result = 1;
break;
}
Could someone please shed some light on the error? I can probably try to skip this table but I'd prefer not to.
[EDIT]
mysql --version
mysql ver 14.14 Distrib 5.6.35, for Linux (x86+64) using Editine wrapper
[/EDIT]
Edit:
Seems that the code is indeed OK and the strncpy is OK. I mistakenly read that the allocation was twice the length of the string but the length was still only one length of the string.
The reason why you see that error is because you are using a string which is not null terminated. This is caused by the fact that strncpy does not null-terminate the string if it exceeds the given limit and the limit you use is the actual length of the string:
memset( str_data1, '\0', str_length1 );
strncpy( str_data1, catalog_name, str_length1 );
params[0].buffer_length = strlen( str_data1 );
A better way to do this would be to use either snprintf(3) that does null terminate the string or by using the std::string constructor that takes a const char* and a length as parameters.
I am trying to read an xml file in Qt, which I successfully generated using a different method. Here is my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Project>
<EditorTheme>NULL</EditorTheme>
<Modules>
<Module>
<Name>Module_Renderer</Name>
<Position>471,164</Position>
<Size>200,100</Size>
<Locked>true</Locked>
<Visible>true</Visible>
</Module>
<Module>
<Name>Module_Console</Name>
<Position>200,229</Position>
<Size>256,192</Size>
<Locked>true</Locked>
<Visible>false</Visible>
</Module>
<Module>
<Name>Module_ResourceToolkit</Name>
<Position>1049,328</Position>
<Size>200,100</Size>
<Locked>true</Locked>
<Visible>true</Visible>
</Module>
<Module>
<Name>Module_CellEditor</Name>
<Position>542,564</Position>
<Size>200,100</Size>
<Locked>true</Locked>
<Visible>false</Visible>
</Module>
</Modules>
</Project>
And here is some code that I am using to parse this file:
Project ProjectLoader::loadLastProject( ConsoleModule* console ) {
Project project;
// load xml
QFile file( "C:/Users/Krynn/Desktop/LastProject.xml" );
if( !file.open( QFile::ReadOnly | QFile::Text ) ) {
// print error cannot open
}
QXmlStreamReader reader;
console->outputDisplay->append( "Test" );
reader.setDevice( &file );
reader.readNext();
while( !reader.atEnd() && !reader.hasError() ) {
reader.readNext();
if( reader.isStartElement() ) {
QString name = reader.name().toString();
if( reader.name() == "Project" ) {
reader.readNextStartElement();
if( reader.name().toString() == "EditorTheme" ) {
// Append Project theme
console->outputDisplay->append( "Theme Detected: " + reader.name().toString() + " " + reader.readElementText() );
}
reader.readNextStartElement();
if( reader.name().toString() == "Modules" ) {
// how do I proceed??
console->outputDisplay->append( QString( "" ) + " " + reader.name().toString() + " " + reader.readElementText() );
}
}
}
}
if( reader.hasError() ) {
console->outputDisplay->append( "XML error: " + reader.errorString() );
} else if( reader.atEnd() ) {
console->outputDisplay->append( "End of XML File Reached" );
}
file.close();
return project;
}
And here is some visual output for what that code gives me:
Really, I just don't know how I would go about loading all the module data within the xml file. I was using a plain text file previously to store all this stuff, but now I want to upgrade. Any help would be greatly appreciated.
Nevermind I figured it out.
Project ProjectLoader::loadLastProject( ConsoleModule* console ) {
Project project;
// load xml
QFile file( "C:/Users/Krynn/Desktop/LastProject.xml" );
if( !file.open( QFile::ReadOnly | QFile::Text ) ) {
// print error cannot open
}
QXmlStreamReader reader;
reader.setDevice( &file );
reader.readNext();
int count = 0;
while( !reader.atEnd() ) { //&& !reader.hasError()
reader.readNext();
if( reader.isStartElement() ) {
if( reader.name().toString() == "Module" ) {
WindowModuleSaveData data;
reader.readNextStartElement();
data.name = reader.readElementText(); // name
reader.readNextStartElement();
data.position = convertStringToQPoint( reader.readElementText() );
console->outputDisplay->append( convertQPointToString(data.position) );
reader.readNextStartElement();
data.size = convertStringToQSize( reader.readElementText() );
reader.readNextStartElement();
data.isLocked = reader.readElementText() == "true" ? true : false;
reader.readNextStartElement();
data.isVisible = reader.readElementText() == "true" ? true : false;
project.modules.push_back( data );
console->outputDisplay->append("Loaded A Module");
}
count++;
}
}
console->outputDisplay->append( QString::number( count ) );
if( reader.hasError() ) {
console->outputDisplay->append( "XML error: " + reader.errorString() );
} else if( reader.atEnd() ) {
console->outputDisplay->append( "End of XML File Reached" );
}
file.close();
return project;
}
The above code may be error prone, because it assumes what the next child may be instead of actually testing for it. Good enough for now though.