How can I read a *.json file and put the output on a std::string?
I have this sample, but I always get null on std::string.
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <rapidjson/ostreamwrapper.h>
#include <fstream>
#include <iostream>
using namespace rapidjson;
using namespace std;
void main()
{
ifstream ifs("input.json");
IStreamWrapper isw(ifs);
Document d;
d.ParseStream(isw);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
std::string jsonStr(buffer.GetString());
if(jsonStr == "null")
std::cout << "is null..." << std::endl; //<--always here!
else
{
std::cout << jsonStr.c_str() << std::endl;
d["ip"] = "123456789";
ofstream ofs("output.json");
OStreamWrapper osw(ofs);
Writer<OStreamWrapper> writer2(osw);
d.Accept(writer2);
}
}
This is my json file:
{
"ip" : "192.168.0.100",
"angle x": 20,
"angle y": 0,
"angle z": 0
}
You need to check for all the errors before converting to std::string. Make sure that the file is open for reading / writing and the parsing is successful i.e. the JSON is valid. GetParseError() and GetErrorOffset() are the functions to validate parsing.
I've used your example and enhanced it. Hope you won't mind. :-)
Here's a working example:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/ostreamwrapper.h>
int main()
{
using namespace rapidjson;
std::ifstream ifs { R"(C:\Test\Test.json)" };
if ( !ifs.is_open() )
{
std::cerr << "Could not open file for reading!\n";
return EXIT_FAILURE;
}
IStreamWrapper isw { ifs };
Document doc {};
doc.ParseStream( isw );
StringBuffer buffer {};
Writer<StringBuffer> writer { buffer };
doc.Accept( writer );
if ( doc.HasParseError() )
{
std::cout << "Error : " << doc.GetParseError() << '\n'
<< "Offset : " << doc.GetErrorOffset() << '\n';
return EXIT_FAILURE;
}
const std::string jsonStr { buffer.GetString() };
std::cout << jsonStr << '\n';
doc[ "ip" ] = "127.0.0.1";
std::ofstream ofs { R"(C:\Test\NewTest.json)" };
if ( !ofs.is_open() )
{
std::cerr << "Could not open file for writing!\n";
return EXIT_FAILURE;
}
OStreamWrapper osw { ofs };
Writer<OStreamWrapper> writer2 { osw };
doc.Accept( writer2 );
return EXIT_SUCCESS;
}
Related
I wrote a simple code using cpprestsdk. I use a map (records) as a member of CommandHandler class, and manipulate it in a public method (has_record()).
it works before handler.open().wait() runs, but when I call it in a request, it crashes!
Here is my code:
#define BOOST_DATE_TIME_NO_LIB
#include <string>
#include <vector>
#include <cpprest/uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/asyncrt_utils.h>
using namespace std;
using namespace web;
using namespace http;
using namespace utility;
using namespace http::experimental::listener;
class CommandHandler
{
public:
CommandHandler(utility::string_t url);
pplx::task<void> open() { return m_listener.open(); }
pplx::task<void> close() { return m_listener.close(); }
bool has_record();
private:
std::map< std::string, unsigned int > records;
void handle_get_or_post(http_request message);
http_listener m_listener;
};
bool CommandHandler::has_record()
{
return records.size() > 0 && records.find("1") != records.end();
}
CommandHandler::CommandHandler(utility::string_t url) : m_listener(url)
{
m_listener.support(methods::GET, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
m_listener.support(methods::POST, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
}
void CommandHandler::handle_get_or_post(http_request request)
{
if(this->has_record())
request.reply(status_codes::OK, 1);
else
request.reply(status_codes::OK, 0);
};
int main(int argc, char** argv)
{
try
{
utility::string_t address = U("http://127.0.0.1:9595");
uri_builder uri(address);
auto addr = uri.to_uri().to_string();
CommandHandler handler(addr);
if(handler.has_record())
std::cout<<"work!";
handler.open().wait();
ucout << utility::string_t(U("Listening for requests at: ")) << addr << std::endl;
ucout << U("Press ENTER key to quit...") << std::endl;
std::string line;
std::getline(std::cin, line);
handler.close().wait();
}
catch (std::exception& ex)
{
ucout << U("Exception: ") << ex.what() << std::endl;
ucout << U("Press ENTER key to quit...") << std::endl;
std::string line;
std::getline(std::cin, line);
}
return 0;
}
I found the problem but I don't understand why it throws. The problem is in this line of code:
request.reply(status_codes::OK, 0);
That 0 throws an exception
I am trying to use the string content read from one program into another program. I have put some sample code to reproduce the example. I have a main function
//main.cpp
#include "read.h"
#include "read_fasta.h"
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
index();
read_fasta_file(argc,argv);
std::cout << " : " << content << std::endl;
std::cout << "Length of fasta file: " << content.length() << std::endl;
return 0;
}
I read fasta file
//read_fasta.cpp
#include <iostream>
#include <fstream>
#include "read_fasta.h"
std::string content;
int read_fasta_file(int argc, char **argv)
{
std::ifstream input(argv[1]);
std::string line, name;
while( std::getline( input, line ).good() ){
if( line.empty() || line[0] == '>' ){ // Identifier marker
if( !name.empty() ){ // Print out what we read from the last entry
std::cout << name << " : " << content << std::endl;
name.clear();
}
if( !line.empty() ){
name = line.substr(1);
}
content.clear();
} else if( !name.empty() ){
if( line.find(' ') != std::string::npos ){ // Invalid sequence--no spaces allowed
name.clear();
content.clear();
} else {
content += line;
}
}
}
if( !name.empty() ){ // Print out what we read from the last entry
std::cout << name << " : " << content << std::endl;
std::cout << "Length of fasta file: " << content.length() << std::endl;
}
return 0;
}
Header file of read_fasta.cpp
//read_fasta.h
#ifndef read_fasta_h
#define read_fasta_h
#include <iostream>
#include <string>
#include <fstream>
int read_fasta_file(int argc, char **argv);
extern std::string content;
#endif
Till now every thing works fine. Now i try to use the std::string content in another cpp progam.
//read.cpp
#include <iostream>
#include <string>
#include "read.h"
void index()
{
std::cout<<"Do U see any printing :"<<content<<std::endl;
}
Header file for read.cpp
//read.h
#ifndef read_h
#define read_h
#include <iostream>
#include <string>
#include <vector>
void index();
extern std::string content;
#endif
But there seem to be nothing in std::string content in read.cpp program. I am missing something.
I've been trying to store the lines of a text file in a list in C++. Better, I've been trying to store each word of each line of the text file in a string that is part of a list of strings, but it seems that I'm doing it in the wrong way.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
using namespace std;
int main()
{
FILE *f= fopen("teste.txt", "r");
size_t len= 100; // valor arbitrário
char *line= (char*)malloc(len);
std::list<string> mylist;
if (!f)
{
perror("teste.txt");
exit(1);
}
while (getline(&line, &len, f) > 0)
{ //THE REAL PROBLEM
for (std::list<string>::iterator it = mylist.begin(); it != mylist.end(); it++){
*it=line;
cout << *it << '\n';
}
}
if (line)
free(line);
fclose(f);
return 0;
}
The exact problem is that this doesn't give any result. It compiles but nothing results from this.
Thanks in advance.
Change your while loop as follows:
while (getline(&line, &len, f) > 0)
{
mylist.push_back(line);
cout << mylist.back() << '\n';
}
You cannot access any non initialized items from a std::list<>.
Also NOTE you should make line a std::string, and omit the malloc() / free() calls from your code.
2nd NOTE: Use std::ifstream instead of FILE* for an input file stream.
Here's the fully fixed (no more errors/exceptions on ideone) code sample:
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <exception>
#include <errno.h>
#include <stdlib.h>
int main()
{
try
{
std::ifstream f("teste.txt");
if(!f)
{
std::cerr << "ERROR: Cannot open 'teste.txt'!" << std::endl;
exit(1);
}
std::string line;
std::list<std::string> mylist;
while (std::getline(f,line))
{
mylist.push_back(line);
std::cout << mylist.back() << std::endl;
}
}
catch(const std::exception& ex)
{
std::cerr << "Exception: '" << ex.what() << "'!" << std::endl;
exit(1);
}
exit(0);
}
You can not assign a char* value to std::string by using '=' operator.
Change
*it=line to
it->assign(line,line+strlen(line);
I need to write two programs write.cpp & read.cpp to run simultaneously. One of them write(overwrite) to a file and the other one reads from it.
Basically, there is always only one line in the file.
write.cpp performs the operation successfully but read.cpp doesn't show anything. Using tail -f also shows incorrect result.
write.cpp:
#include <stdio.h>
#include <ctime>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream myfile;
int i = 70;
char c;
while(i <85)
{
myfile.open ("example.txt");
c = i++;
myfile << c << endl;
myfile.close();
sleep(1);
}
return 0;
}
read.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
sleep(1);
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
May I know which part of both programs causes the problem and how may I solve it?
You're doing the right thing in the writer, but once you've read to end of file, the input stream becomes unusable until the fail condition is set. The best solution is probably to do exactly what you're doing in the writer: open and close the file each time in the read loop.
Be aware that there will be a moment when the file is empty; when you open the file for writing in the writer, it will be truncated, and if the reader happens to try to read at precisely this moment, it will find an empty file. (It's no big problem; just be aware of it, maybe skipping the sleep if you find an empty line.)
To add some detail to my answer to your previous question, here is how you could use Boost's interprocess communication to achieve this if you insist on using a file for ipc.
A writer may look like this:
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <fstream>
#include <iostream>
int main()
{
using namespace boost::interprocess;
std::string line, shared_filename = "shared";
{
std::ofstream create_shared_file(shared_filename.c_str());
}
for (;;)
{
std::cout << "Enter some text: ";
std::cin >> line;
try
{
file_lock lock(shared_filename.c_str());
scoped_lock<file_lock> lock_the_file(lock);
std::ofstream shared_file(shared_filename.c_str(), std::ofstream::trunc);
shared_file << line << std::endl;
shared_file.flush();
}
catch (interprocess_exception const& e)
{
std::cerr << e.what() << std::endl;
}
}
}
The corresponding reader:
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <fstream>
#include <iostream>
#include <unistd.h>
int main()
{
using namespace boost::interprocess;
std::string line, shared_filename = "shared";
for (;;)
{
try
{
file_lock lock(shared_filename.c_str());
std::cout << "Waiting for file lock..." << std::endl;
sharable_lock<file_lock> lock_the_file(lock);
std::cout << "Acquired file lock..." << std::endl;
std::ifstream shared_file(shared_filename.c_str());
shared_file >> line;
if (line.empty())
{
std::cout << "Empty file" << line << std::endl;
}
else
{
std::cout << "Read: " << line << std::endl;
}
}
catch (interprocess_exception const& e)
{
std::cerr << "Could not lock " << shared_filename << ": " << e.what() << std::endl;
}
std::cout << "Sleeping..." << std::endl;
sleep(2);
}
}
I'm trying using pipes with boost libraries, I just want to execute a background program(e.g.: ls) and get it's output in a string(like you can do with fopen and fread), but I really can't get why I have no output with this code:
#include <iostream>
#include <cstdio>
#include <sstream>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
int
main(int argc, char** argv)
{
using namespace boost::iostreams;
if(argc < 2) {
return -1;
}
FILE* p = popen(argv[1], "r");
if(! p) {
std::cerr << "error open pipe" << std::endl;
return -2;
}
int fd = fileno(p);
std::stringstream ss;
ss << fd;
std::string s = ss.str();
file_descriptor_source pdesc(s);
stream_buffer<file_descriptor_source> pstream(pdesc);
std::istream is(&pstream);
std::string out;
while(is) {
std::getline(is, out);
std::cout << out << std::endl;
}
pstream.close();
pdesc.close();
pclose(p);
return 0;
}
Thanks in advance.
It seems you are trying to open a boost::file_descriptor_source from a "path" which contains the file descriptor number. However, a file of this name probably doesn't exist. What you probably meant to use is something like this:
if (FILE* p = popen(argv[1], "r"))
{
boost::iostreams::file_descriptor_source d(fileno(p), boost::iostreams::close_handle);
boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> pstream(d);
std::cout << &pstream;
pclose(p);
}