segmentation fault reading json file - c++

I need to read the information contained in a json file like this:
{"first":10, "second":"0", "P1":"1.e-20","P2":"1000","P3":"1000","P4":"1000","P5":"1"}
Since I do not have experience with this issue, I started by playing with the short code you can see below these lines. It does compile with no problem but it gives a segmentation fault back upon execution. The file general.json is in the same folder. The information contained in the json file is correctly printed in the screen if I comment the last line. Could anyone tell me what am I doing wrong?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fstream> // fstream.h in old versions of g++
#include <iostream> //para cout
#include <sstream>
#include <json/json.h>
using namespace std;
int main() {
struct json_object *new_json, *json_arr, *json_reg, *json_field;
string line;
stringstream jsonfile;
ifstream json("file.json", ios::in);
{getline(json, line); do {jsonfile << line;} while (getline(json, line));}
json.close();
cout << jsonfile.str().c_str();
new_json=json_tokener_parse(jsonfile.str().c_str());
json_field=json_object_object_get(json_reg, "first");
}

You are using the json_reg pointer without initializing it and the function dereferences it. You are (most likely) using json-c where:
json_object_object_get calls json_object_object_get_ex on the object
json_object_object_get_ex does switch(jso->o_type) dereferencing an invalid pointer

Related

Read a file with C++ in linux server

I am trying to read a file which is placed in the desktop through C++ program in linux server.I have mentioned the path correctly,but it's not reading the file. I have tried the same program in windows platform it's working fine.I'm able to read the file.
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string line;
ifstream file;
file.open("/home/xxx/Desktop/nodeinfo.txt",ios::in);
if(!file.is_open())
{
cout<<"error";
}
getline(file,line);
cout<<line;
return 0;
}
could someone help me how to solve this problem. Is there any specific path format for linux platform. Thanks

Set read cursor fails

I am using boost to read a file
But when I set seekg to a position (~20000) in the file,
I get a runtime error
Microsoft C++ exception:
boost::exception_detail::clone_impl`<`boost::exception_detail::error_info_injector`<`std::ios_base::failure>>> at memory location 0x00EEC874.
Code:
ifstream if("file.bin",std::ios::binary)
if (if.is_open())
{
boost::iostreams::stream<boost::iostreams::mapped_file_source>is(fs);
is.seekg(20000, is.beg); //error is here
//// read
}
That code shouldn't compile. If it does, file a bug report with the compiler vendor.
if is a reserved keyword.
Assuming you messed up the code sample, (because you also had missing ;), it should just work but you may just have missing files/error handling:
Live On Coliru
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
int main() {
std::ifstream ifs("main.cpp",std::ios::binary);
if (ifs.is_open())
{
boost::iostreams::stream<boost::iostreams::mapped_file_source> is("main.cpp");
if (is.seekg(200, is.beg))
std::cout << is.rdbuf();
}
}

C++ Using RapidXml parsing XML File, Wrapper Class, parse_error expect >

I'm trying to use the RapidXML to parse my XML file. And I did it following the example here. Instead of doing the parsing in the main function, I wrote a wrapper class called XMLParser to do the parsing job. And this really gives me a headache.
The XMLParser.hpp:
#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>
#include "rapidxml/rapidxml.hpp"
using namespace std;
using namespace rapidxml;
class XMLParser {
public:
XMLParser() {};
XMLParser(const std::string &xmlString): xmlCharVector(xmlString.begin(), xmlString.end())
{
//xmlCharVector.push_back('\0');
parseXML();
}
XMLParser(const std::vector<char> &_xmlVector):xmlCharVector(_xmlVector)
{
/* xmlCharVector.push_back('\0'); */ // already done in main.cpp
if (xmlCharVector != _xmlVector) //And it turns out they're the same....
std::cout << "The two vectors are not equal" << std::endl;
else
std::cout << "They are the same" << std::endl;
parseXML();
}
private:
std::vector<char> xmlCharVector;
rapidxml::xml_document<> doc;
void parseXML();
};
The XMLParser.cpp:
#include "XMLParser.hpp"
using namespace std;
using namespace rapidxml;
void XMLParser::parseXML()
{
doc.parse<0>(&xmlCharVector[0]);
}
And here is the main.cpp:
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <fstream>
#include "XMLParser.hpp"
using namespace std;
using namespace rapidxml;
int main(int argc, char **argv)
{
xml_document<> doc;
xml_node<> *root_node;
ifstream theFile("beer.xml");
vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());
buffer.push_back('\0');
doc.parse<0>(&buffer[0]);
root_node = doc.first_node("MyBeerJournal");
xml_node<> *engine = root_node->first_node("Brewery");
//The above code works pretty well, and I can get the element I want in XML file.
//The problem occurs when I tried to use the XMLParser
XMLParser xmlParser(buffer);
return 0;
}
The parsing process in the main function works pretty well. But when I tried to use the function in my wrapper class parseXML(), then error occured:
terminate called after throwing an instance of 'rapidxml::parse_error'
what(): expected >
Abort (core dumped)
Originally I have other code in this function, but I commented them all, and find that even with the single line doc.parse<0>(&xmlCharVector[0]);. Why it works well in main.cpp while not in the wrapper class? I really can't figure it out. Could anybody help me?
I've found out the reason... This stupid problem really takes me a long time to debug. I'm writing it here so that anyone ran into it (hope not) could save his time. The problem lies exactly in the code doc.parse<0>(&buffer[0]) in the main function. Before executing this line of code, the buffer(type of vector<char>) is like this: (by printing the vector to console)
<MyBeerJournal>
<Brewery name="Founders Brewing Company" location="Grand Rapids, MI">
<Beer name="Centennial" description="IPA" rating="A+" dateSampled="01/02/2011">
"What an excellent IPA. This is the most delicious beer I have ever tasted!"
</Beer>
</Brewery>
.....
.....
</MyBeerJournal>
It's the same with original xml file. After executing the above code, the buffer(type of vector<char>) becomes something like this:
<MyBeerJournal
<Breweryname"Founders Brewing Company location"Grand Rapids, MI>
<Beername"Centennial description"IPA rating"A+ dateSampled"01/02/2011>
"What an excellent IPA. This is the most delicious beer I have ever tasted!"
/Beer>
</Brewery>
As you can see, some angel brackets disappeared. and some other things like double quote has also been changed. So the wrapper class constructor copied the modified "xml buffer", and this not well formatted xml vector will certainly cause the second doc.parse<0>(&xmlCharVector[0]); in the wrapper class to fail. I don't know why the library writer needs to modify the char vector passed in, because the subsequent xml analysis is not relevant to the original char vector once the DOC has been created.

How can I solve the error concerning libogg

#include <iostream>
#include <assert.h>
#include <fstream>
#include <map>
#include <ostream>
#include "ogg.h"
using namespace std;
#pragma comment(lib,"libogg.lib")enter code hereenter
void readogg();
void readogg(){
ifstream stream;
ifstream file("invitation.ogg", ios::in | ios::binary);
ogg_sync_state state;
ogg_sync_init(&state);
ogg_page page;
if (ogg_sync_pageout(&state, &page) != 1)
{
char* buffer = ogg_sync_buffer(&state, 8092);
assert(buffer);
file.read(buffer, 8092);
int bytes = stream.gcount();
ogg_sync_wrote(&state, bytes);
}
ogg_stream_state s_state;
ogg_packet pack;
☆ ogg_stream_pagein(&s_state, &page);
ogg_page_packets(&page);
ogg_stream_packetout(&s_state, &pack);
}
This is my code what I was invisible mending. I have another code about main but it have not a problem. I debugged step by step, so I think ☆ code might have a error and the result might do not connects or saves information of 'invitation.ogg' file.
I couldn't find answer anywhere and this is my final chance keeping on this code. I'm not Thanks to read my question and I really hope to find my answer.

Run-time error reading a .gz file using boost::iostreams and zlib

I am trying to read a .gz file and print the text content on screen by using boost::iostreams. This is just a simple experiment to learn about this library, and I am using the "directors.list.gz" file from IMDb (ftp://ftp.fu-berlin.de/pub/misc/movies/database/) as my input file.
My code compiles, via MSVC-10, but the process aborts when executed. There's not much information from the error message except for the error code being R6010.
Can someone please point me a direction in terms of what may have caused this and how do I make this work?
This library looks pretty neat and I do hope to use it correctly. Thanks a lot for helping.
#include <fstream> // isalpha
#include <iostream> // EOF
#include <boost/iostreams/categories.hpp> // input_filter_tag
#include <boost/iostreams/operations.hpp> // get
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/filter/zlib.hpp>
using namespace std;
namespace io = boost::iostreams;
int main()
{
if(true)
{
string infile_path = "c:\\Temp\\directors.list.gz";
ifstream infile(infile_path, ios_base::in | ios_base::binary);
io::filtering_streambuf<io::input> in; //filter
in.push(io::zlib_decompressor());
in.push(infile);
//output to cout
io::copy(in, cout);
}
return 0;
}
The gzip file format has an additional header around the zlib data, which zlib can't read.
So you want to use boost's gzip_decompressor instead of zlib_decompressor.
in.push(gzip_decompressor());
Note you'll need to include boost/iostreams/filter/gzip.h instead of boost/iostreams/filter/zlib.h.
Here's a working example of streaming a GZIP file:
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/copy.hpp>
using namespace boost::iostreams;
int main()
{
std::ifstream file("hello.gz", std::ios_base::in | std::ios_base::binary);
filtering_streambuf < input > in;
in.push(gzip_decompressor());
in.push(file);
boost::iostreams::copy(in, std::cout);
}
You'll find more information on specific boost::iostreams filters lurking here in boost's documentation: http://www.boost.org/doc/libs/1_46_1/libs/iostreams/doc/quick_reference.html#filters
I also feel I should point out that your code didn't compile with gcc: in the C++ standard library, the ifstream constructor takes a const char *, not a std::string. (I'm not sure about Microsoft's version).