【发布时间】:2016-07-28 14:49:25
【问题描述】:
在屏幕截图中使用修改后的代码进行了更新
有一个 Sybase 数据库设置,并且提供的 isql 脚本可以连接到它。我现在要做的是能够连接到数据库以在其上运行一些 sql 命令(使用或不使用 isql 脚本)并将输出存储在数据结构中以处理 c++ 中的每一行。我在网上找到了一小段代码,它应该允许我通过将命令作为 c 样式字符串传递来运行 isql 脚本,但是尝试编译 cpp 文件会出现 popen 和 pclose 未在范围内声明的错误。如果有其他连接数据库的方法,或者如果您知道如何解决该错误,请告诉我。
原代码:
#include <stdio.h>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
std::shared_ptr<FILE> pipe( popen(cmd, "r"), pclose());
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer, 128, pipe.get()) != NULL)
result += buffer;
}
return result;
}
Compiling code with GNU++14 in response to ildjarn
Compiling code with lambda function for pipe in response to max66
【问题讨论】:
-
尝试使用
-std=gnu++14而不是-std=c++14进行编译,并将pclose()更改为pclose或&pclose。 -
更新了错误信息和代码的截图