2016-07-28 33 views
0

與修改後的代碼更新SCREENSHOTS上的Sybase表運行在C++

有Sybase數據庫的設置和所提供的ISQL腳本連接到它的工作原理SQL命令。我現在想要做的是能夠連接到數據庫以在其上運行一些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

+0

嘗試用編譯'-std = GNU ++ 14'代替'-std = C++ 14',和變化'pclose函數()''到或pclose''&pclose'。 – ildjarn

+0

更新了錯誤消息和代碼的屏幕截圖 –

回答

0

的範圍不聲明?

你確定嗎?

我的編譯器說pclose()需要一個參數。

我建議您使用自定義刪除器修改pipe聲明;一個簡單的lambda函數應該可以工作;像

std::shared_ptr<FILE> pipe(popen(cmd, "r"), [](auto ptr) { if (ptr) pclose(ptr); }); 
+0

是的,我添加了一個編譯錯誤的圖像,並再次使用您的lambda函數。 –

+0

@AndreyChoi - 不知道;抱歉。我的編譯器編譯你的代碼,所以我想這個問題不是嚴格的與它有關。我看到你使用g ++;在這個平臺上(OS,CPU等)? – max66

+0

Windows 7 Enterprise 64位 Intel Xeon E5-1603 使用Cygwin 64位 –