Api

哪段程式碼可以讓我檢查是否已找到塊然後執行操作?

  • March 31, 2016

我對 C++ 比較陌生,我想知道是否有人可以幫助我。我正在尋找一段程式碼,它將循環直到節點找到一個塊,然後在找到一個塊時列印一個簡單的輸出,如“找到塊”。

謝謝!

您可以簡單地記錄某處的值,並通過重複bitcoind getblockcount呼叫查看該值何時發生變化。getblockcount

#include <string>
#include <iostream>
#include <stdio.h>

std::string exec(char* cmd) {
   FILE* pipe = popen(cmd, "r");
   if (!pipe) return "ERROR";
   char buffer[128];
   std::string result = "";
   while(!feof(pipe)) {
       if(fgets(buffer, 128, pipe) != NULL)
           result += buffer;
   }
   pclose(pipe);
   return result;
}

int main(){
   int count;
   count = stoi(exec("bitcoind getblockcount"));
   for(;;){
       int new_count = stoi(exec("bitcoind getblockcount"));
       while(count < new_count){
           std::cout << "Block found." << std::endl;
           count++;
       }
       system("sleep 1"); // There are other ways of sleeping. This is the quick and dirty way.
   }
   return 0;
}

公平地說,這是對 Luca 的想法和<https://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c>的抄襲。

引用自:https://bitcoin.stackexchange.com/questions/23934