I am a beginner to C++ and SQLlite and trying to compile code which can manipulate the results of a query from SQLite.
I am having difficulties in storing the results to a .txt file, which will enable me to manipulate results, and don't know where to start,
As a result, I can only see one row in MA.txt however I would like to store all of the results,
I want to store results into a .txt file because after I store the results, I have to divide the results into predefined lengths and find max and min values and report the first row and last row as well.
#include <iostream>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
#include <sqlite3.h>
#include <string>
#include <locale>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <vector>
using namespace std;
static int callback2(void *data, int argc, char **argv, char **azColName)
{
ofstream os;
os.open("MA.txt");
os << argv[0] << endl;
return 0;
os.close();
}
int main(int argc, char* argv [])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
const char* data = "Callback function called";
rc = sqlite3_open("test.db", &db);
if (rc){
cout << "Can't open database: %s\n" << sqlite3_errmsg(db);
exit(0);
}
string sql = "SELECT * from forex;";
rc = sqlite3_exec(db, sql.c_str(), callback2, (void*) data, &zErrMsg);
if (rc != SQLITE_OK){
cout << "SQL error:" << zErrMsg;
sqlite3_free(zErrMsg);
}
return 0;
}
I changed the code however I got "os does not name a type" error while compiling,
where should I put the offsting, sorry I am really a noobie:(
#include <iostream>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
#include <sqlite3.h>
#include <string>
#include <locale>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <vector>
using namespace std;
ofstream os;
os.open("MA.txt");
static int callback2(void *data, int argc, char **argv, char **azColName)
{
os << argv[0] << endl;
return 0;
}
int main(int argc, char* argv [])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
const char* data = "Callback function called";
rc = sqlite3_open("test.db", &db);
if (rc){
cout << "Can't open database: %s\n" << sqlite3_errmsg(db);
exit(0);
}
string sql = "SELECT * from forex;";
rc = sqlite3_exec(db, sql.c_str(), callback2, (void*) data, &zErrMsg);
if (rc != SQLITE_OK){
cout << "SQL error:" << zErrMsg;
sqlite3_free(zErrMsg);
}
return 0;
os.close();
}
I think that this is because of the way you are opening the file. You are opening it every time you read a new record and this causes it to go back to the beginning every time.
One way to fix this is to declare the ofstream outside the function and open it outside the function and close it at the very end. Another way to fix it is to open the ofstream with the std::app flag set, so that it will append to the file instead of rewriting it.
Another thing is that you are returning '0' from the call back function. You need to return SQLITE_OK to tell it to continue.
Not sure if this will work because I haven't tested it, but try this code:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
#include <sqlite3.h>
#include <string>
#include <locale>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <vector>
using namespace std;
static int callback2(void *data, int argc, char **argv, char **azColName) {
ofstream os("MA.txt", ios::app);
os << argv[0] << endl;
os.close();
return SQLITE_OK;
}
int main(int argc, char* argv []) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
const char* data = "Callback function called";
rc = sqlite3_open("test.db", &db);
if (rc){
cout << "Can't open database: %s\n" << sqlite3_errmsg(db);
exit(0);
}
char sql[21] = "SELECT * from forex;";
rc = sqlite3_exec(db, sql.c_str(), callback2, NULL, &zErrMsg);
if (rc != SQLITE_OK){
cout << "SQL error:" << zErrMsg;
sqlite3_free(zErrMsg);
}
return 0;
}
Related
I know there is one in C, Sleep(ms), but is there one for C++? I am trying to return an error, then print to the console, then sleep enough for the user to read it before returning the errorcode. Code in C would be:
#include <stdio.h>
#include <windows.h>
int main (int argc, const char *argv[]) {
char *err = "Have an error!";
printf("Error: %s. Program terminating in 5 seconds...", err);
Sleep(5000);
return 1;
}
You could include <windows.h> and just call the WinApi function Sleep just as you would from C. This is mostly pure C++ :
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
using namespace std;
int main (int argc, const char *argv[]) {
string err = "Have an error!";
cout << "Error: " << err << ". Program terminating in 5 seconds..." << endl;
std::chrono::milliseconds timespan(5000);
std::this_thread::sleep_for(timespan);
return 1;
}
I'm trying to write a function that has mmap within it, however when I try to access the memory from main(), it gets a segfault. Does anyone have any idea why?
Please ignore the MPI headers - it's for the later part of the project. I have commented out the mprotect line to see that it is an mmap fault as opposed to the handler not necessarily working
net_map.cpp:
#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "net_map.h"
using namespace std;
void handler(int sig, siginfo_t* info, void* other)
{
void* address = info->si_addr;
cout << "\nSegfault Detected! [Address: " << address << "]\n" << endl;
int unprotectresult = mprotect(address, SIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
if (unprotectresult == 0)
{
cout << "\nSuccessful mprotect (memory unprotected)!\n" << endl;
}else
{
cout << "\nMprotect unsuccessful\n" << endl;
}
}
void netmap (char filename[], char* mapped)
{
int file;
file = open(filename, O_RDWR);
mapped = (char*) mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0);
if (mapped == MAP_FAILED)
{
cout << "\nMap Failed!" << endl;
}
cout << mapped << endl;
}
main.cpp
#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <unistd.h>
#include <array>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <array>
#include "net_map.h"
using namespace std;
int main(int argc, char* argv[])
{
struct sigaction segaction;
memset(&segaction, 0, sizeof(segaction));
segaction.sa_flags = SA_SIGINFO;
sigemptyset(&segaction.sa_mask);
segaction.sa_sigaction = handler;
sigaction(SIGSEGV, &segaction, NULL);
int i;
char* mapped;
networkpage sheet;
char filename[] = "hello.txt";
netmap(filename, mapped);
sheet.address = (void*)mapped;
cout << "\nAddress: " << sheet.address << endl;
//mprotect(sheet.address, SIZE, PROT_NONE);
memcpy(sheet.address, "k", 1);
munmap(sheet.address, SIZE);
return 0;
}
My question is how to correctly write a protobuf message in text format to a file. In the program below I create a NetParameter object which is a message
field in message field in caffe.proto.
When I call print() and PrintToString() they return failure.
I can print the mesaage on the console with printf("%s", data.c_str()); but notting is written to file?
#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include <string>
#include "caffe.pb.h"
#include <iostream>
#include <caffe/caffe.hpp>
using namespace std;
using google::protobuf::Message;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::TextFormat;
int main()
{
caffe::NetParameter param;
const char *filename = "./test.prototxt";
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1)
cout << "File not found: " << filename;
google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);
param.set_name("AlexNet");
param.add_input_dim(0);
param.add_input_dim(1);
param.add_input_dim(2);
param.set_input_dim(0, 3);
param.set_input_dim(1, 3);
param.set_input_dim(2, 3);
std::string data;
bool success = google::protobuf::TextFormat::PrintToString(param, &data);
std::cout << "bool is " << success << std::endl;
printf("%s", data.c_str());
bool success1 = google::protobuf::TextFormat::Print(param, output);
std::cout << "bool is " << success << std::endl;
close(fd);
return 0;
}
Does anybody know how to redirect stderr into a file without buffering in? if it is possible could you show me a simple code in c++ language for linux (Centos 6) operating system..?!
In C
#include <stdio.h>
int
main(int argc, char* argv[]) {
freopen("file.txt", "w", stderr);
fprintf(stderr, "output to file\n");
return 0;
}
In C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int
main(int argc, char* argv[]) {
ofstream ofs("file.txt");
streambuf* oldrdbuf = cerr.rdbuf(ofs.rdbuf());
cerr << "output to file" << endl;
cerr.rdbuf(oldrdbuf);
return 0;
}
Another way to do this is with the following dup2() call
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <unistd.h>
using std::cerr;
using std::endl;
int main() {
auto file_ptr = fopen("out.txt", "w");
if (!file_ptr) {
throw std::runtime_error{"Unable to open file"};
}
dup2(fileno(file_ptr), fileno(stderr));
cerr << "Write to stderr" << endl;
fclose(file_ptr);
}
I'm having an issue where only one of my 5 test rows will output in C++. My code is:
#include <cstdio>
#include <sqlite3.h>
#include <windows.h>
#include <wincrypt.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
/*Definitions*/
sqlite3 *db;
void *arg;
char *err;
const char* stmt = "SELECT * from table";
/*End of Definitions*/
int exec(void *arg, int argc, char **argv, char **column) {
int i;
for(i = 0; i < argc; i++) {
cout << column[i] << ": " << argv[i] << endl;
}
cout << "------" << endl;
}
int main() {
int rc = sqlite3_open("test.sqlite", &db); /*Open db "test.sqlite"*/
if(!rc) {
while(true) {
sqlite3_exec(db, stmt, exec, arg, &err);
if(err) {
break;
}
}
}
/*Ending Stuffz (NOTHING BEYOND THIS POINT)*/
cin.get();
return 0;
}
I am not getting any errors; it is purely just outputting the first row. Any help is appreciated, thanks.
Just return 0 in the end of exec function
Explanation:
In function 'exec" when it return nothing, the database server acts like the function is terminated by somehow (like something corrupt the function and made an error) so it just stop sending data because the call back function terminated with an error.... so when we return 0 we say that the function "exec" is working normally so it keeps sending data ... and if you return any other integer it will deal with it like the function terminated by an error and stop sending data. I faced the same issue and I solved it by making the callback function (exec) return 0.