C++, windows->linux porting, mapfile problem - c++

I'm porting a small C++ console application from windows to linux, GCC 4.3.2. When compiling I get strange error that I'm unable to solve.
Labels.cpp: In function ‘void DumpSymbols()’:
Labels.cpp:68: error: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’
Labels.cpp:68: error: initializing argument 2 of ‘std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]’
Labels.cpp:
#include <string>
#include <fstream>
#include <iostream>
#include "stdafx.h"
using namespace std;
#include "Opcodes.h"
#include "Labels.h"
Label LABELS[1024];
int labelcounter = 0;
int OffsetCounter = 0;
void AddLabel(string name, int line)
{
LABELS[labelcounter].name = name;
LABELS[labelcounter].line = line;
LABELS[labelcounter].offset = OffsetCounter;
printf("Adding label: %s[0x%X]\n", name.c_str(), OffsetCounter);
labelcounter++;
}
bool IsLabel(string name)
{
for(int i=0;i<labelcounter;i++)
{
if (LABELS[i].name.compare(name) == 0)
{
return true;
}
}
return false;
}
int GetOffset(string lbl)
{
for(int i=0;i<labelcounter;i++)
{
if (LABELS[i].name.compare(lbl) == 0)
{
printf("Refers to label '%s':0x%X\n", lbl.c_str(), LABELS[i].offset);
return LABELS[i].offset;
}
}
return -1;
}
void DumpSymbols()
{
ofstream mapfile("symbols.map", ios::out|ios::beg); //this line causes error
//mapfile.write(
char numbuf1[32];
itoa(labelcounter, numbuf1, 10);
mapfile.write((string(numbuf1) + "\n").c_str(), strlen(numbuf1)+1);
for(int i=0;i<labelcounter;i++)
{
string dump;
char numbuf[32];
itoa(LABELS[i].offset, numbuf, 10);
dump = string(LABELS[i].name) + "\t" + string(numbuf) + "\n";
mapfile.write(dump.c_str(), strlen(dump.c_str()));
}
}
stdafx.h:
#pragma once
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cstdlib>
Thanks.

Just remove "|ios::beg":
ofstream mapfile("symbols.map", ios::out);
It's type is ios_base::seekdir, which is not an opening mode; it's for seeking to a position. You'll automatically be at the beginning anyway.

Is ios::beg really a valid value for the mode parameter of the ofstream constructor?
According to http://www.cplusplus.com/reference/iostream/ofstream/ofstream.html it's not.
I guess what happened is that you accidentally borrowed it from a call to ofstream::seekg (where it is a valid parameter) to enforce that the writing will start from the beginning of the file rather than the end of it.
If you are trying to force the file to be completely replaced if it already existed, try using ios::trunc instead of ios::beg.

Related

Ambiguous pointer; <SiHCollection> is ambiguous

below I've posted my code which is meant to store hits collections in HCE (hit collection of events).
The code compiles successfully but on running the program, the following error is printed to the terminal seven times:
< SiHCollection> is ambiguous.
I have a feeling it is because I am using namespace std although I don't know how to amend the code. Any thoughts?
#include "SiSD.h"
#include "SiHit.h"
#include "G4HCofThisEvent.hh"
#include "G4Step.hh"
#include "G4ThreeVector.hh"
#include "G4SDManager.hh"
#include "G4ios.hh"
#include "G4UnitsTable.hh"
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
extern ofstream outfile;
SiSD::SiSD(G4String name)
:G4VSensitiveDetector(name)
{
collectionName.insert("SiHCollection");
}
SiSD::~SiSD(){ }
void SiSD::Initialize(G4HCofThisEvent* HCE)
{
SiHCollection = new SiHitsCollection(SensitiveDetectorName,
collectionName[0]);
static G4int HCID = -1;
if(HCID<0)
{
HCID = G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
}
HCE->AddHitsCollection(HCID, SiHCollection);
}
G4bool SiSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
if(aStep->GetTrack()->GetTrackID() > 0) {
G4double edep = aStep->GetTotalEnergyDeposit();
if(edep==0) return false;
SiHit* aHit = new SiHit();
aHit->SetEdep(edep);
SiHCollection->insert(aHit);
return true;
} else return false;
}

Assertion `IsArray()' failed (RapidJSON)

I was testing the RapidJSON library earlier today to see if I could parse a document with nested values, and for some reason I couldn't come up with a solution to the errors I was getting. I searched around Google and Stack Overflow for an hour or two and couldn't find a fix. Here is the code along with the errors:
main.cpp:
#include <iostream>
#include <SFML/Graphics.hpp>
#include "rapidjson/document.h"
#include "include.hpp"
int main() {
unsigned int input = 1;
tile output;
output = LoadTile("../locations.json", input);
std::cout << output.x << std::endl;
return 0;
}
load.cpp
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "include.hpp"
using namespace rapidjson;
tile LoadTile(std::string fileName, unsigned int number) {
FILE* file = fopen(fileName.c_str(), "r");
char buffer[2048];
FileReadStream stream(file, buffer, 2048);
Document doc;
doc.ParseStream(stream);
tile output;
Value& tileNumber = doc[number];
if(!tileNumber.IsObject()) {
output.overflow = true;
output.x = 0;
output.y = 0;
output.type = "\0";
}else{
output.x = tileNumber[0]["x"].GetInt();
output.y = tileNumber[0]["y"].GetInt();
output.type = tileNumber[0]["type"].GetString();
}
return output;
}
include.hpp:
#include <iostream>
#include <SFML/Graphics.hpp>
#include "rapidjson/document.h"
struct tile {
int x;
int y;
std::string type;
bool overflow = false;
};
tile LoadTile(std::string fileName, unsigned int number);
CMakeLists.txt:
cmake_minimum_required(VERSION 2.6)
project(test)
set(EXECUTABLE_NAME "test")
add_executable(${EXECUTABLE_NAME} main.cpp load.cpp include.hpp)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin})
locations.json:
{
1:[
{"x":32},
{"y":32},
{"type":"water_c"}
]
}
Errors:
test: /home/.../rapidjson/document.h:1547:rapidjson::GenericValue<Encoding, Allocator>::operator[](rapidjson::SizeType) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; rapidjson::SizeType = unsigned int]: Assertion `IsArray()' failed.
Aborted (core dumped)
I know it's not the JSON formatting, I've tried everything. Unless there's something really wrong with it. I'm running this on Xubuntu 16.10. Thanks to anyone that can help.
Your JSON is invalid. In JSON, keys must be strings, written with double quotes. More details here.
I suggest using JSONLint to validate JSON strings.
The valid JSON looks like this (1 in double quotes):
{
"1": [{
"x": 32
}, {
"y": 32
}, {
"type": "water_c"
}]
}

c++ put functions in separate source files

Currently I have an unique source file (*.cpp) where all my functions are working right. Now i'm trying to take some of them out into separate source files and including them into main source with no success.
My current project is as follows:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
using namespace std;
using std::cout;
using std::ifstream;
/*This is one of the functions to be put in separate file:*/
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15;
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre);
if (inputFile.is_open())
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End of function 'ReadPageAsignations'
/*This is another function where my function "ReadPageAsignations' get called -- btw, I want also this function to be in a separate source file.*/
void DeliverHtml (const char* page){//const char* RutayNombre ) {
string *p;
char * pch;
size_t pos;
string RutayNombre;
RutayNombre = "../Substructure/Templates/" + SearchConfigValue( "../Substructure/Conf/Config-Templates.txt", "htmlTemplate:");
const char *RutayNombreConfigCompos = "../Substructure/Conf/Config-Composition.txt";
string RutayNombreParaInsertar;
string token, token1, token2;
string line, lineRead, lineToInsert;
char * StrToTokenize2;
string StrToTokenize1;
p=ReadPageAsignations( RutayNombreConfigCompos, page); //Here, I call the function I want in a separate file
...
}
/*And here is the main() function*/
int main()
{
char *value = "page=Home";
if (NULL!=strstr(getenv("QUERY_STRING"), "page="))
{
value = getenv("QUERY_STRING");
}
char *posCh = strstr(value, "=");
DeliverHtml(&posCh[0]+1);
return 0;
}
For the first function, I have tried creating the header file 'ReadPageAsignations.h' and a source file 'ReadPageAsignations.cpp'.
Header file 'ReadPageAsignations.h' containing:
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
Source file 'ReadPageAsignations.cpp' for separate function containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using std::cout;
using std::ifstream;
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15; /*El numero de elementos debe coincidir con el iterador en la función Deliverhtml.*/
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre); //Abre el archivo y lo asigna al stream inputFile.
if (inputFile.is_open()) //Chequea que el archivo esté abierto.
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End function
and, main project containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h" //Here I #include the function definition file (header)
using namespace std;
using std::cout;
using std::ifstream;
...
}
I've got a lot of compiling errors:
\ReadPageAsignations.h|4|error C2143: syntax error : missing ';' before '*'|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
main.cpp|20|error C2872: 'string' : ambiguous symbol|
...
I'm working Code::blocks 13.12 with MS Visual C++ 2005/2008 compiler.
any help will be highly appreciated, thanks in advance.
The error is telling you that when it tried to parse the header file it encountered the symbol string and doesn't recognize it. Adding #include <string> to your header file and fully qualifying the string type as std::string should correct the problem.
You should put #include <string> in your header file and remove it from your .cpp file
as following:
main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h"
...
note: including header file with the same name of .cpp file , include both.
ReadPageAsignations.h
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
#include <string> //<-----This line, include string header
std::string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
ReadPageAsignations.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include "ReadPageAsignations.h" // <--- add the header file here
//#include <string> <---remove it already included in the header file
using namespace std;
//using std::cout; <--remove this you already used namespace std
//using std::ifstream; <--remove this you already used namespace std
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
... } //End function

How to find the index in Poco::DeflatingOutputStream

Hi I am new to usage of Poco , can you please help me to find a way to get the index/position during the writing into deflating stream so that I can truncate the invalid data and make sure my file contains only valid data.
#include <stdexcept>
#include <stdarg.h>
#include <map>
#include <iostream>
#include <cstring>
#include <fstream>
#include <Poco/DeflatingStream.h>
#include <stdio.h>
#include <limits>
#include <stdio.h>
#include <unistd.h>
using namespace std;
std::ofstream* ostr;
Poco::DeflatingOutputStream* ofstr;
string fileName="/home/lamb/Cpp/simple.gzip";
bool written = false;
// int lastsucessfulwrite;
compress(){
*ofstr << "\t<xyz>\n";
*ofstr << "\t</xyz>\n";
*ofstr << " who=\"";
*ofstr << "/>\n";
written = true;
/* "lastsucessfulwrite" How to store the index of ofstr , in case of normal files we use ftell but in DeflatingOutputStream how to get index so that I can erase it later based on this value */
}
timer(){
sleep(2);
// 2 second
written = false ;
}
close(){
ofstr->close();
delete ofstr;
ofstr = NULL;
ostr->close();
delete ostr;
ostr = NULL;
}
int main(){
ostr = new std::ofstream;
ostr->exceptions(std::ofstream::failbit|std::ofstream::badbit);
ostr->open(_fileName.c_str(), std::ios::binary | std::ios::app);
ofstr = new Poco::DeflatingOutputStream(*_ostr,
Poco::DeflatingStreamBuf::STREAM_GZIP);
ofstr->precision(std::numeric_limits<double>::digits10);
string data1 = "hello';
string data2 = "hello';
string data3 = "hello';
written = false ;
timer()//start
compress(data1);
if(written)
{
compress(data2);
}
if(written)
{
compress(data2);
}
if(written)
{
compress(data3);// timeup and time() is inovked and part of compress() is executed
}
// Now I would like to use lastsucessfulwrite as the key and truncate the paritally witten data3
// In case of normal file we use "truncate" system call
close();
}
You can use any standard C++ stream functions with Poco streams.
streampos pos = ofstr->tellp()

opencv_NormalizeHist.cpp:47:34: error: 'NormalizeHist' was not declared in this scope

I have written the code to access opencv(Mainly used for image processing) function from Scilab(numerical computation software). When I run bilder gateway file, I am encountering below error.
opencv_NormalizeHist.cpp:47:34: error: 'NormalizeHist' was not declared in this scope.
#include <numeric>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
extern "C"
{
#include "api_scilab.h"
#include "Scierror.h"
#include "BOOL.h"
#include <localization.h>
#include "../common.h"
int opencv_NormalizeHist(char *fname, unsigned long fname_len)
{
SciErr sciErr;
int iRows=0,iCols=0;
int *piAddr2 = NULL;
//checking input argument
CheckInputArgument(pvApiCtx, 2, 2);
CheckOutputArgument(pvApiCtx, 0, 0) ;
//Define histogram
Mat hist;
retrieveImage(hist,1);
double *factor;
//for value of factor
sciErr = getVarAddressFromPosition(pvApiCtx,2,&piAddr2);
if (sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
sciErr = getMatrixOfDouble(pvApiCtx, piAddr2, &iRows, &iCols ,&factor);
if(sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
NormalizeHist(hist, factor[0]); //Normalizing hist
string tempstring = type2str(hist.type());
char *checker;`enter code herek
checker = (char *)malloc(tempstring.size() + 1);
memcpy(checker, tempstring.c_str(), tempstring.size() + 1);
returnImage(checker,hist,1); //here, remove the temp as a parameter as it is not needed, and instead add 1 as the third parameter. 1 denotes that the first output argument will be this variable
free(checker); //free memory taken up by checker, i missed this earlier
//Assigning the list as the Output Variable
AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx) + 1;
//Returning the Output Variables as arguments to the Scilab environment
ReturnArguments(pvApiCtx);
return 0;
}
/* ==================================================================== */
}